javascript - Vue.js "track-by $index",如何单独渲染列表项

标签 javascript vue.js

直到最近我还在使用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-showtrack-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-fortrack-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/

相关文章:

d3.js - d3 作为 Vue 组件

javascript - 调用方法时页面刷新(不需要)

javascript - 如何在导航到不同页面之前执行 onclick?

javascript - VS 代码中的 JSDoc,用于记录具有模块类型的函数

javascript - 如何在 Javascript (jQuery) 中使用递归函数创建动态 html 列表

vue.js - VUE2js : How to have component re-render after its props change?

javascript - 通过 setInterval 添加输入不起作用

javascript - Magento : Moving content to the review tab on the product page

javascript - 悬停选项,或 JavaScript

javascript - Vue 中测量溢出不正确