2016-10-29 50 views
16

如何在列表中使用计算属性。我正在使用VueJS v2.0.2。VueJS如何使用v-for的计算属性

这里的HTML:

<div id="el"> 
    <p v-for="item in items"> 
     <span>{{fullName}}</span> 
    </p> 
</div> 

这里的Vue公司代码:

var items = [ 
    { id:1, firstname:'John', lastname: 'Doe' }, 
    { id:2, firstname:'Martin', lastname: 'Bust' } 
]; 

var vm = new Vue({ 
    el: '#el', 
    data: { items: items }, 
    computed: { 
     fullName: function(item) { 
      return item.firstname + ' ' + item.lastname; 
     }, 
    }, 
}); 

回答

22

不能为每个迭代计算的特性。理想情况下,这些items中的每一个将是它们的自己的组件,因此每个可以具有其自己的fullName计算的属性。

如果您不想创建user组件,您可以执行的操作是使用方法。您可以从computed产权移动fullNamemethods,那么你可以使用它像:

{{ fullName(user) }} 

另外,侧面说明,如果你发现自己需要一个参数传递给computed你可能想的方法来代替。

11

什么你错过了这里是你的items是一个数组,其中包含的所有项目,但computed是单fullName,刚刚无法表达所有fullName S IN items。在视图

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 
    } 
}); 

然后:试试这个

<div id="el"> 
    <p v-for="(item, index) in items"> 
     <span>{{fullNames[index]}}</span> 
    </p> 
</div> 

草案提出一定的工作方式,但我们可以与计算道具做到这一点,我认为这是在反复比method一个更好的设计,尤其是当应用程序变大时。此外,在某些情况下,computedmethod相比性能有所提高:http://vuejs.org/guide/computed.html#Computed-Caching-vs-Methods

+0

使用此功能突出显示':class'指令中的行比一种方法更好。 – hitautodestruct