【问题标题】:Vue.js "track-by $index", how to render list items individuallyVue.js“track-by $index”,如何单独渲染列表项
【发布时间】:2016-04-03 15:06:19
【问题描述】:

直到最近,我还在使用 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。

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    解决方案毕竟相当简单,并且生成的代码更精简。完全取消 v-for 和 track-by $index 指令并使用计算属性代替了诀窍:

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

    在 html 文件中,只需像往常一样添加计算属性 currentTweet,带有小胡子标签,此处解释为 raw html:

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

    因此不需要这样的东西:

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

    JsFiddle here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-26
      • 1970-01-01
      • 1970-01-01
      • 2018-01-06
      • 1970-01-01
      • 1970-01-01
      • 2012-07-23
      • 1970-01-01
      相关资源
      最近更新 更多