vue数组和对象进行 watch 和 watchEffect 对比

const arr1 = ref([]);
    const arr2 = reactive([]);
    const obj1 = ref({});
    const obj2 = reactive({});
    watchEffect(() => {
        console.log("watchEffect arr1", arr1.value);
        console.log("watchEffect arr2", arr2);
        console.log("watchEffect obj1", obj1.value);
        console.log("watchEffect obj2", obj2);
    });
    watch(
        arr1,
        (newValue, oldValue) => {
            console.log("watch arr1", newValue, oldValue);
        },
        {}
    );
    watch(
        arr2,
        (newValue, oldValue) => {
            console.log("watch arr2", newValue, oldValue);
        },
        {}
    );
    watch(
        obj1,
        (newValue, oldValue) => {
            console.log("watch obj1", newValue, oldValue);
        },
        {}
    );
    watch(
        obj2,
        (newValue, oldValue) => {
            console.log("watch obj2", newValue, oldValue);
        },
        {}
    );
    setTimeout(() => {
        arr1.value.push(111);
    }, 2000);
    setTimeout(() => {
        arr2.push(222);
    }, 2000);
    setTimeout(() => {
        obj1.value["aaa"] = 111;
    }, 2000);
    setTimeout(() => {
        obj2["bbb "] = 222;
    }, 2000);

以上写法,数组和对象修改,仅在 watch 的监听下, reactive定义的数组和对象可以被监听到改变

 

const arr1 = ref([]);
    const arr2 = reactive([]);
    const obj1 = ref({});
    const obj2 = reactive({});
    watchEffect(() => {
        // console.log("layerList1", layerList);
        // console.log("layerList2", layerList.value);
        // console.log("currentClickLayer111", currentClickLayer);
        console.log("watchEffect arr1", arr1.value);
        console.log("watchEffect arr2", arr2);
        console.log("watchEffect obj1", obj1.value);
        console.log("watchEffect obj2", obj2);
    });
    watch(
        arr1,
        (newValue, oldValue) => {
            console.log("watch arr1", newValue, oldValue);
        },
        { deep: true }
    );
    watch(
        arr2,
        (newValue, oldValue) => {
            console.log("watch arr2", newValue, oldValue);
        },
        { deep: true }
    );
    watch(
        obj1,
        (newValue, oldValue) => {
            console.log("watch obj1", newValue, oldValue);
        },
        { deep: true }
    );
    watch(
        obj2,
        (newValue, oldValue) => {
            console.log("watch obj2", newValue, oldValue);
        },
        { deep: true }
    );
    setTimeout(() => {
        arr1.value.push(111);
    }, 2000);
    setTimeout(() => {
        arr2.push(222);
    }, 2000);
    setTimeout(() => {
        obj1.value["aaa"] = 111;
    }, 2000);
    setTimeout(() => {
        obj2["bbb "] = 222;
    }, 2000);

以上写法,通过设置 watch 选项,deep:true,支持深度监听,ref 和 reactive 创建的对象和数组都可以被 watch 监听到

官方文档

 

总结:

watch :

通过 ref 创建的变量,如果是数组或者对象,需要增加 deep:true 来进行深度监听

通过 reactive 创建的变量,如果是数组或者对象,默认会进行深度监听

watchEffect:

不支持对象和数组的监听

 

 

posted @ 2023-04-04 18:55  蓓蕾心晴  阅读(111)  评论(0编辑  收藏  举报