简体   繁体   中英

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?

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.

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')" )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM