简体   繁体   中英

vuejs 2 observation doesn't work

I can't figure out why vuejs observation don't work on a very simple scenario. When the model "asker" is updated, computed props should automagically update value to 3. Why is this not working ? Fiddle is here https://jsfiddle.net/w1zz9cjs/3/

<div id="simulator">
<c-simulator-form v-bind:subject="asker"></c-simulator-form>
</div>

Vue.component('c-simulator-form', {
  props: ['subject'],
  template: '<div class="c-simulator-form">{{thesize}}</div>',
  computed: {
    thesize: function() {
      return _.size(this.subject);
    }
  }
});

var vm = new Vue({
  el: '#simulator',
  data: {
    asker: {
      a: 1,
      b: 2
    }
  }
});

vm.asker['c'] = 3;

Why this doesn't work is because Vue cannot detect property addition or deletion of any newly added properties for objects, ie, 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 })

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