Vue2 watch deep 原理
const options = {template: '<h1></h1>',data() {return {obj: {name: 'name'}};},created() {this.watchValue();setTimeout(() => {this.obj.name = 'name1111'}, 1000)},methods: {watchValue() {this.$watch('obj', (newVal, oldVal) => {console.log('newVal:', newVal, 'oldVal:', oldVal);},{deep: false})// this.$watch(表达式 | 函数 ,回调, 配置项)//// 1. 假如obj 是一个对象 watch 这个对象 那么obj.a = 122 会不会触发回调// A: 只有加deep = true 才会触发回调}}};
const options = {template: '<h1></h1>',data() {return {arr: []};},created() {this.watchValue();setTimeout(() => {this.arr.push(122)}, 5000)},methods: {watchValue() {this.$watch('arr', (newVal, oldVal) => {console.log('newVal:', newVal, 'oldVal:', oldVal);},{deep: false})// this.$watch(表达式 | 函数 ,回调, 配置项)//// 1. 假如arr 是一个数组 对其执行push 操作会不会有回调// A: 会触发回调}}};
deep 做的事情:
最终会触发travers函数 对监听的对象进行遍历 并读取每一个key值 触发 getter进行依赖收集
Vue3 watch deep 原理
const { createApp } = Vue;const Counter = {data() {return {counter: 0,arr: []}},created() {this.$watch('arr', (newVal, oldVal) => {console.log('newVal:', newVal, 'oldVal:', oldVal);},{deep: false});setTimeout(() => {this.arr.push(122)}, 1000);}}createApp(Counter).mount('#counter')// 这里watch 不会生效 只有deep 为true 才会 生效// why?// Vue3 官方文档解释: 当侦听的值是一个对象或者数组时,对其属性或元素的任何更改都不会触发侦听器,因为它们引用相同的对象/数组:// 为了发现对象内部值的变化,可以在选项参数中指定 deep: true。这个选项同样适用于监听数组变更。
