VueJS How can I use computed property with v-for

后端 未结 4 1935
天命终不由人
天命终不由人 2020-11-29 21:12

How can I use computed property in lists. I am using VueJS v2.0.2.

Here\'s the HTML:

4条回答
  •  隐瞒了意图╮
    2020-11-29 21:25

    What you're missing here is that your items is an array, which holds all the items, but the computed is a single fullName, which just can't express all the fullNames in items. Try this:

    var vm = new Vue({
        el: '#el',
        data: { items: items },
        computed: {
            // corrections start
            fullNames: function() {
                return this.items.map(function(item) {
                    return item.firstname + ' ' + item.lastname;
                });
            }
            // corrections end
        }
    });
    

    Then in the view:

    {{fullNames[index]}}

    The way Bill introduces surely works, but we can do it with computed props and I think it's a better design than method in iterations, especially when the app gets larger. Also, computed has a performance gain compared to method on some circumstances: http://vuejs.org/guide/computed.html#Computed-Caching-vs-Methods

提交回复
热议问题