vue3 watch 监听数组 对象

解决方法(数组触发两次)

const numbers = reactive([1, 2, 3, 4])

watch(
() => [...numbers],
(numbers, prevNumbers) => {
console.log(numbers, prevNumbers);
})

numbers.push(5) // logs: [1,2,3,4,5] [1,2,3,4]

解决的问题

1、数组deep监听触发两次
2、新旧值一致

对象

尝试检查深度嵌套对象或数组中的属性更改仍然需要deep选项为true
Attempting to check for changes of properties in a deeply nested object or array will still require the deep option to be true

const state = reactive({
id: 1,
attributes: {
name: "",
},
});

watch(
() => state,
(state, prevState) => {
console.log(
"deep ",
state.attributes.name,
prevState.attributes.name
);
},
{ deep: true }
);

state.attributes.name = "Alex"; // Logs: "deep " "Alex" "Alex"

引用

vue3官方文档

posted @ 2021-04-24 16:29  一二时间  阅读(7075)  评论(0)    收藏  举报