VueJS如何将计算属性与v-for一起使用 [英] VueJS How can I use computed property with v-for
问题描述
如何在列表中使用计算属性。我正在使用VueJS v2.0.2。
How can I use computed property in lists. I am using VueJS v2.0.2.
这是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;
},
},
});
推荐答案
您无法为每次迭代创建计算属性。理想情况下,每个项目
都是他们的拥有组件,因此每个人都可以拥有自己的 fullName
计算属性。
You can't create a computed property for each iteration. Ideally, each of those items
would be their own component so each one can have its own fullName
computed property.
如果你不想创建用户
组件,你可以做什么,是用一种方法代替。您可以将 fullName
从计算
属性移至方法
,然后你就可以使用它:
What you can do, if you don't want to create a user
component, is use a method instead. You can move fullName
right from the computed
property to methods
, then you can use it like:
{{ fullName(user) }}
另外,请注意,如果您发现自己需要将参数传递给计算
您可能想要一种方法。
Also, side note, if you find yourself needing to pass an arguments to a computed
you likely want a method instead.
这篇关于VueJS如何将计算属性与v-for一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!