Ifnot
Ifnot

Reputation: 5103

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 ?

Upvotes: 10

Views: 11556

Answers (2)

Ifnot
Ifnot

Reputation: 5103

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

Upvotes: 22

Jacob Goh
Jacob Goh

Reputation: 20855

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

Upvotes: 7

Related Questions