[Vuejs]-Vuejs 2 observation doesn't work

2👍

Why this doesn’t work is because Vue cannot detect property addition or deletion of any newly added properties for objects, i.e., the properties have to be already there for the object to be reactive.

Therefore, if you write

vm.asker['b'] = 4;

Vue will be able to detect the change (https://jsfiddle.net/n4qe3def/1/) while

vm.asker['c'] = 3;

doesn’t work because asker.c is not reactive in Vue.

One way to fix this is like what dfsq wrote in the comment:

vm.$set(vm.asker, 'c', 3) or Vue.set(vm.asker, 'c', 3)

But if you actually want to assign multiple new properties, the easier way is actually creating a new object for asker instead (https://jsfiddle.net/8618cx2h/2/):

vm.asker = Object.assign({}, vm.asker, { c: 3, d: 4, e: 5 })
👤kevguy

Leave a comment