vue3 watch 数组

vue3 watch 数组

基于官方项目进行测试

https://github.com/vuejs/vue-next-webpack-preview

 

需要观察一个数组的变化,再该数组中的数据变化时通知

const { ref, watch, watchEffect, computed, value } = require("vue");

let list = ref([]);

watch(list, (val) => {
	console.log("watch1", list.value);
});
watch(list.value, (val) => {
	console.log("watch2", list.value.length);
});

setTimeout(() => {
	list.value.push(1);
}, 1000);

setTimeout(() => {
	list.value[0] = 2;
}, 2000);
setTimeout(() => {
	list.value = [1, 2, 3, 4, 5];
}, 3000);

但是实际测试中只能在重新赋值时才会触发更新

 

即便使用watch观察list.value或list.value.length 也无法触发更新

 

 

https://www.jianshu.com/p/72f7e247b4b0

需要设置deep属性为true

const { ref, watch, watchEffect, computed, value } = require("vue");

let list = ref([]);

watch(
	list,
	(val) => {
		console.log("watch1", list.value);
	},
	{
		// lazy: true,
		deep: true,
		// flush: "pre" | "post" | "sync",
		// flush: "pre",
		// onTrack: (e) => console.log("onTrack"),
		// onTrigger: (e) => console.log("onTrigger"),
	}
);
watch(list, (val) => {
	console.log("watch2", list.value.length);
});

setTimeout(() => {
	list.value.push(1);
}, 1000);

setTimeout(() => {
	list.value[0] = 2;
}, 2000);
setTimeout(() => {
	list.value = [1, 2, 3, 4, 5];
}, 3000);
默认情况下,所有的 watcher 回调都会在当前的 renderer flush 之后被调用。这确保了在回调中 DOM 永远都已经被更新完毕。如果你想要让回调在 DOM 更新之前或是被同步触发,可以使用 flush 选项: