vue3.5 watch更新结果 。对于3.5 和 3.3 两者之间的差别,3.3computed内响应式数据改变(不管结果数据是否一样)就会执行watch的第一个函数 ,这样会造成性能消耗(一样的结果不会执行watch第二个函数) 3.5先检查computed结果数据是否改变,改变后执行watch第一个函数
vue3.5 watch更新结果
import { onMounted, nextTick, ref, reactive, computed, watch, watchEffect } from 'vue'
const state = ref({
// 是否显示loading
loading: true,
a: 1,
b: 2
})
// 满足1和2两个条件被满足时 -> 触发computed函数更新(初始不会执行函数)
// 1.被访问
// 2.computed是脏数据(也就是isDirty = true)
// 2.1初始时 isDirty = true
// 2.2当被访问时且是脏数据后触发computed的函数更新,然后isDirty = false // 打印 console.log("computed update");
// 2.3当依赖的值变化时 isDirty = true (如果有绑定的函数,就派发事件给访问了num函数(绑定,在这里是watch第一个函数),绑定了的函数再次访问,接下来就相当于2.2)
const num = computed(() => {
console.log("computed update");
return state.value.a + state.value.b
})
watch(() => {
// 在执行这个函数之前 刷新num computed 查看数据是否变化 是:执行 否:不执行
console.log("watch call111");
return num.value
}, (newVal, oldVal) => {
console.log('watch更新111', oldVal, 'to', newVal)
})
watch(() => {
// 在执行这个函数之前 刷新num computed 查看数据是否变化 是:执行 否:不执行
console.log("watch call222");
return num.value
}, (newVal, oldVal) => {
console.log('watch更新222', oldVal, 'to', newVal)
})
console.log("=====>");
/**
// 改变如下数据
* state.value.a++
* state.value.b--
* 打印
watch call111 // watch 初始执行第一个函数
computed update // 目前computed在初始状态还是脏数据 && 被访问了(谁访问的?答:watch第一个函数)
watch call222 // 在这里computed 不是脏数据了 所以不执行 computed update(条件只满足其中之一,被访问了)
=====>
computed update //这一步打印过程: 在上一步 执行了++和-- -> computed是脏数据(因为数据改变了)后computed派发数据给绑定的函数,然后watch第一个函数被调用之前会刷新num的computed(但是num这个数据总和没变,不会触发watch) -> 刷新了肯定会触发comouted函数更新 -> 没有下一步了
*/
测试题
// 改变如下数据
- state.value.a++
思考 ........ 答案如下
| 打印 | |
|---|---|
| watch call111 | |
| computed update | |
| watch call222 | |
| =====> | |
| computed update | |
| watch call111 | |
| watch更新111 3 to 4 | |
| watch call222 | |
| watch更新222 3 to 4 |