Solve the problem that Vue2.0 Watch object attribute changes can’t be listened

I encountered a problem, parent component to the sub-component, and listened to an attribute of incoming objects. Find that subcomponents use Deep Watch that changes in objects can not be observed, and today I finally found this problem and solution.

Solve

What is the problem? Restricted by ES5, Vue.js cannot detect addition or deletion of object properties.

Please refer to https://v1-cn.vuejs.org/guide/reactivity.html

Solution:

This through Vue . $ set (Object, key, value) method

Recreate an object via Object.Assign (), such as this.SomeObject = Object.assign ({}, this.someObject, {a: 1, b : 2})

Code instance

ways
  Method 2  

Export default {data () {return {p: {a: 1}}}, methods: {fun1 () {Console.log ('Click 1111') / / this.pb = 2 // assigns a value by point method, found that the change of the P can be observed this. $ set (this.p, 'b', 2) // First solution, you can view the log see that you have listened To change}, fun2 () {console.log ('Click 2222')THIS.P = Object.assign ({}, this.p, {c: 3})}}}, watch: {p: {handler (cval, oval) {console.log ('-------- ') Console.log (CVAL, OVAL)}

Summary
Individual recommendation uses the second solution, the code is more elegant. The first solution If there is a number of values, multi-line $ set () statement.
The above solves the problem that the Vue2.0 Watch object attribute changes is not the content of Xiaobian sharing to everyone. I hope I can give you a reference, I hope everyone will support Tumi Cloud.

© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment