Farzher
Farzher

Reputation: 14563

Vue.js How to add new property to a repeated array object?

html

<div v-repeat=dudes>{{a}}, {{b}}</div>

js

dudes = [{a:1}, {a:2}, {a:3}]

new Vue({
  el: 'body',
  data: {dudes: dudes}
})
dudes[0].b = 'test'

Trying to set dudes[0].b = 'test' doesn't work.

http://jsbin.com/dogadutiqa/1/edit

Unless I define dudes with a b property to begin with dudes = [{a:1, b:null}, {a:2}, {a:3}]

How do I add new properties?

Upvotes: 2

Views: 3320

Answers (2)

Sebasti&#225;n Grignoli
Sebasti&#225;n Grignoli

Reputation: 33432

For the latest Vue version (2.2.0 at the time of this answer) this is what you should do:

Instead of dudes[0].b = 'test' just do:

Vue.set(dudes[0],'b','test');

from inside the method, or:

$set(dudes[0],'b','test')

from inside the view template (like in @click="$set(dudes[0],'b','test')")

Upvotes: 2

Leo
Leo

Reputation: 13838

Due to the limitations of ES5, Vue cannot detect properties directly added to or deleted from an object.

You need to use $add method to declare the property, so that it could be watched. Also if you want to remove a property, you need $delete method.

Upvotes: 3

Related Questions