如何使用ractive在阵列中设置新的DOM条目?
问题描述:
我有一个修改数组的Ractive实例。当新值出现在数组中时,我想要突出显示相应的元素。我目前通过对新创建的元素进行一些样式来做到这一点。 这是jsfiddle。如何使用ractive在阵列中设置新的DOM条目?
var ractive = new Ractive({
el: 'main',
template: `
<h1>Hello {{name}}!</h1>
{{ #things:index }}
<p>{{ things[index] }}</p>
{{ /things }}
`,
data: function(){
return {
things: [
'banana',
'carrot'
]
}
},
oncomplete: function(){
var component = this;
setTimeout(function(){
component.set('things', ['apple', 'banana', 'carrot'])
}, 5 * 1000)
}
});
唯一的问题是,由于ractive重复使用元素,造型出现在错误的元素上。
时'banana', 'carrot']
改为['apple', 'banana', 'carrot']
,该'carrot'
元素突出,与新值对应的'apple'
元素,而不是你会看到。
在数组中设置新条目的最佳方式是什么?
答
使用recentlyAddedThings
缓存来添加缓存的添加项目。这里有一个working jsfiddle:
var ractive = new Ractive({
el: 'main',
template: `
{{ #things:index }}
<p class="{{ #if recentlyAddedThings.includes(things[index]) }}new{{ /if }}">
{{ things[index] }}
</p>
{{ /things }}
`,
data: function(){
return {
things: [
'banana',
'carrot'
],
recentlyAddedThings: [
]
}
},
oncomplete: function(){
var component = this;
var addThing = function(newThing){
var things = component.get('things')
var newThing = newThing
things.push(newThing)
component.set('things', things.sort())
component.push('recentlyAddedThings', newThing)
}
setTimeout(function(){
addThing('apple')
}, 2 * 1000)
setTimeout(function(){
addThing('avocado')
}, 3 * 1000)
setTimeout(function(){
addThing('cheese')
}, 4 * 1000)
}
});
答
您应该使用splice
方法
component.splice('things', 0, 0, 'apple'); // Add at zero index
component.splice('things', 1, 0, 'apple'); // Add at first index
,而不是重新设置整个阵列。这相当于Array.splice
方法。
整个代码将如下所示。
var ractive = new Ractive({
el: 'main',
template: `
<h1>Hello {{name}}!</h1>
{{ #things:index }}
<p>{{ things[index] }}</p>
{{ /things }}
`,
data: function(){
return {
things: [
'banana',
'carrot'
]
}
},
oncomplete: function(){
var component = this;
setTimeout(function(){
component.splice('things', 0, 0, 'apple');
}, 5 * 1000)
}
});
@mikemaccana我更新了答案。看一看。 – Thusitha
@mikemaccana我更新了答案。看看 – Thusitha
hmm'splice()'的作品,但我需要的元素/项目的顺序。有没有办法做到这一点? – mikemaccana