直到最近我还在使用v-show
在我的 Vue 实例中一次显示一个数组中的每个元素。我的 html 有以下行:<li v-for="tweet in tweets" v-show="showing == $index">{{{ tweet }}}</li>"
。我的根 Vue 实例是这样构建的(感谢 @Jeff !):
new Vue({
el: '#latest-tweets',
data: function(){
return {
tweets: [],
showing: 0
};
},
methods:{
fetch:function(){
var LatestTweets = {
"id": '706642968506146818',
"maxTweets": 5,
"showTime": false,
"enableLinks": true,
"customCallback":this.setTweets,
"showInteraction": false,
"showUser": false
};
twitterFetcher.fetch(LatestTweets);
},
setTweets: function(tweets){
this.tweets = tweets;
console.log(tweets);
},
rotate: function(){
if(this.showing == this.tweets.length - 1){
this.showing = -1;
}
this.showing += .5;
setTimeout(function(){
this.showing += .5;
}.bind(this), 1000);
}
},
ready:function() {
this.fetch();
setInterval(this.rotate, 10000);
}
一切都很好,直到我遇到重复的值。为了处理这些,我替换了 v-show
与 track-by $index
,如指定here 。我现在的 html 上有这个:<li v-for="tweet in tweets" track-by="$index">{{{ tweet }}}</li>
。问题在于,不是单独渲染每个列表项,而是一次渲染整个列表。
至于上述rotate
方法,因为我不能做 track-by="showing == $index"
,现在已经没用了。据我了解,这是由于 Vue 无法检测到数组长度的变化。似乎有一个解决方法,详见here ,即“用空数组替换项目”,我这样做没有效果。我不知道我错过了什么。
这里有几个 JsFiddles,其中 v-show
和 track-by $index
。
最佳答案
解决方案毕竟相当简单,而且生成的代码也更简洁。完全取消 v-for
和 track-by $index
指令并使用计算属性来解决这个问题:
computed: {
currentTweet: function () {
return this.tweets[this.showing]
}
}
在 html 文件上,只需像平常一样添加计算属性 currentTweet
,并带有 mustache 标记,此处解释为 raw html :
<li>{{{ currentTweet }}}<li>
因此不需要这样的东西:
<li v-for="tweet in tweets" track-by="$index">{{{ tweet }}}</li>
JsFiddle here
关于javascript - Vue.js "track-by $index",如何单独渲染列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36387106/