Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS How can I use computed property with v-for

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;         },     }, }); 
like image 252
Inoyatulloh Avatar asked Oct 29 '16 18:10

Inoyatulloh


People also ask

Can we use computed property in V model?

You can use computed properties to check whether a condition is true, then use v-if within our template to determine whether to display a block of code or not.

How do computed properties work in Vue?

A computed property is used to declaratively describe a value that depends on other values. When you data-bind to a computed property inside the template, Vue knows when to update the DOM when any of the values depended upon by the computed property has changed.


2 Answers

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.

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.

like image 135
Bill Criswell Avatar answered Sep 19 '22 21:09

Bill Criswell


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:

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

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

like image 20
JJPandari Avatar answered Sep 20 '22 21:09

JJPandari