Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS : manually trigger an update into observed object/array

I created a vue object for data reactivity :

let vm = new Vue({
  data () {
    return {
      myData: {}
    }
  },
  watch: {
    myData (value) {
      console.log('changed')
    }
  }
})

When I push / edit / delete into vm.myData, all is ok, the watcher send me changed.

Now, i want to get the changed event only by "touching" vm.myData (without data edition). Can I call an internal method of the observer for this ?

like image 216
Ifnot Avatar asked Feb 26 '18 09:02

Ifnot


2 Answers

Ok I have the solution.

We can trigger the notify() method from the attached observer :

vm.myData.__ob__.dep.notify()

I found it from the source when vuejs patch the original methods in order to put the data reactive.

https://github.com/vuejs/vue/blob/dev/src/core/observer/array.js#L42

like image 140
Ifnot Avatar answered Nov 09 '22 09:11

Ifnot


since it's an object(object is passed by reference, not by value), it can be done like this

vm.myData = Object.assign({},vm.myData);

this create a new object of the exactly same values, but it's a new object so it will trigger watcher.

https://codepen.io/jacobgoh101/pen/RQeLoM?editors=1011

like image 6
Jacob Goh Avatar answered Nov 09 '22 09:11

Jacob Goh