The problem that the method for solving vue watch data is called twice
- 2021-09-12 00:29:24
- OfStack
Background:
Routing structure/video/1. mp4, that is,/video is the parent route,/1. mp4 is the dynamic child route of/video. In the parent route of/video, video information will be obtained through params of url, that is, the corresponding complete video information will be obtained through/1. mp4, and then transmitted to the dynamic child route through props, and then the child route will be displayed through the received video objects
Question:
When the route is switched, that is, when I click on other videos, resulting in dynamic sub-route changes, I listen to the changes of/video parent route and re-obtain video objects according to params of url, and automatically pass them into sub-routes through props. I carry out some operations through watch video objects in sub-routes, and the result is
watch: {
video () {
console.log("test")
}
}
test was printed twice. After one search, it was found that when the child route was switched, data data in the parent route/video would be initialized to the default value, so the video object changed twice, one because the initialization was reset to the default value null object, and the other was the correct data after the request
Ending:
The video object is stored in the vuex, and then the parent route passes the video object in the vuex to the child route
Additional knowledge: When vue watch1 objects or arrays, newvalue and oldvalue1 are like
Why are the values of newval and oldval equal when the depth of watch1 objects is changed by 1 in the official code?
var vm = new Vue({
data: {
a: 1,
c:{
c1:1,
c2:2
}
},
watch: {
'a': function (val, oldVal) {
console.log(val, oldVal,(val== oldVal))
},
// Method name
'b': 'someMethod',
// Depth watcher
'c': {
handler: function (val, oldVal) {
console.log(val, oldVal,(val== oldVal))
},
deep: true
}
}
})
vm.a = 2
vm.c.c1 = 2
Depth independent, but when an object or array is modified (not replaced), the old value will be the same as the new value because they index the same object/array. Vue does not keep a copy of the value before the modification.