In-depth understanding of oldvalue, newValue, and vue. jsoldvalue of $ watch in vue. js
$ Oldvalue and newValue in watch
We all know that the $ watch method is provided in vue. js to listen for object changes, and two objects, oldValue and newValue, are returned in callback.
As the name suggests, these two objects are the values before and after the object changes.
However, during use, I found that these two values are not always expected. Let's take a look at the detailed introduction:
Define data values
Data: {arr: [{name: 'dummy', address: 'shanghai'}, {name: 'dummybear ', address: 'beijing'}], obj: {name: 'dump', address: 'suzhou '}, str: 'hahaha '}
Define watch
watch: { arr: function(newValue, oldValue) { console.log(newValue, oldValue) console.log(JSON.stringify(oldValue) === JSON.stringify(newValue)) }, obj: function(newValue, oldValue) { console.log(newValue, oldValue) console.log(JSON.stringify(oldValue) === JSON.stringify(newValue)) }, str: function(newValue, oldValue) { console.log(newValue, oldValue) console.log(JSON.stringify(oldValue) === JSON.stringify(newValue)) }, }
Define event triggering
methods: { test() { this.arr.push({ name: 9 }) this.$set(this.obj, 'i', 0) this.str = '' }, test1() { this.arr = [{ name: '000' }] this.obj = { name: 999 } this.str = '123' } }
Test result:
- Although the push operation on the array and the $ set operation on the Obj may trigger the watch event, the oldValue and newValue are the same in the results returned by callback. String objects returned as expected
- When assigning values to arrays and Obj in a uniform way, watch triggers and oldValue and newValue are returned as expected.
Other watch tests
Unable to trigger the listener
1. Array
Modifies the value of an attribute of a subobject.
Delete an attribute using native delete
Add an attribute for a subscript ($ set is not used)
Returns a value for a subscript.
2. Object
Modifies the value of an attribute (but triggers the listener for this attribute)
Add an attribute ($ set is not used)
Native delete deletes an attribute
The above summary may be insufficient.
Watch monitoring
Add such a piece of code after the data is modified.
Array
arr = [...arr]
Obj
obj = {...obj}
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.