How can I use computed property in lists. I am using VueJS v2.0.2.
Here's the HTML:
<div id="el">
<p v-for="item in items">
<span>{{fullName}}</span>
</p>
</div>
Here's the Vue code:
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;
},
},
});
What you're missing here is that your
items
is an array, which holds all the items, but thecomputed
is a singlefullName
, which just can't express all thefullName
s initems
. Try this:Then in the view:
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 tomethod
on some circumstances: http://vuejs.org/guide/computed.html#Computed-Caching-vs-MethodsYou 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 ownfullName
computed property.What you can do, if you don't want to create a
user
component, is use a method instead. You can movefullName
right from thecomputed
property tomethods
, then you can use it like:Also, side note, if you find yourself needing to pass an arguments to a
computed
you likely want a method instead.