Vue.js"track-by-$index”;,如何单独呈现列表项

Vue.js "track-by $index", how to render list items individually

本文关键字:何单独 列表 index js quot track-by- Vue      更新时间:2023-11-19

直到最近,我还在Vue实例中使用v-show显示数组中的每个元素,每次一个。我的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);
}

一切都很好,直到我遇到重复的值。为了处理这些问题,我用track-by $index替换了v-show,正如这里所指定的那样。我现在在我的html:<li v-for="tweet in tweets" track-by="$index">{{{ tweet }}}</li>上有了这个。问题是,不是单独渲染每个列表项,而是同时渲染整个列表。

至于上面的rotate方法,由于我不能做track-by="showing == $index",所以现在它是无用的。据我所知,这是由于Vue无法检测到数组长度的变化。这里详细介绍了一种变通方法,即"用空数组替换项",但我没有这样做。我想不出我错过了什么。

以下是几个JsFidles,包括v-showtrack-by $index

解决方案毕竟相当简单,结果代码更精简。完全取消v-fortrack-by $index指令,并使用计算的属性来实现这一点:

computed: {
  currentTweet: function () {
    return this.tweets[this.showing]
  }
}

在html文件中,这只是一个添加计算属性currentTweet的问题,就像你通常会添加的那样,带有一个小胡子标签,在这里被解释为原始html:

<li>{{{ currentTweet }}}<li>

因此不需要这样的东西:

<li v-for="tweet in tweets" track-by="$index">{{{ tweet }}}</li>

Js在此处出价