VUE框架Vue3下使用watch监听ref下没有指向value的Proxy的对象------VUE框架

<template>
    <h1>{
    
    { counter }}</h1>
    <button @click="counter++">按一下</button>
    <h1>{
    
    { data.a.b.c.counter }}</h1>
    <button @click="data.a.b.c.counter++">按一下</button>
</template>

<script>
import {watch,ref} from "vue";
export default {
    name : "App",
    setup(){
        let counter = ref(1);
        let data = ref({
            a : {
                b : {
                    c : {
                        counter : 1
                    }
                }
            }
        });
        // 错误的,因为获取的是一个值
        // watch(counter.value,(newValue,oldValue)=>{
            
        // });
        // 可以监视到,效果和reactive是一样的,因为这里都是一个Proxy对象
        watch(()=>counter.value,(newValue,oldValue)=>{
            console.log(newValue,oldValue)
        });
        // 直接放进去,默认是没有开启深度监视的 
        watch(data,(newValue,oldValue)=>{
            console.log(newValue,oldValue)
        },{immediate:true,immediate:true});
        // 这种可以监视到,因为底层还是Proxy对象
        // 不需要箭头函数去指
        // ref下如果包裹的是一个对象,而且watch没有指向value那个Proxy,而是指向对象本身,就不会开启深度监视
        watch(data.value,(newValue,oldValue)=>{
            console.log(newValue,oldValue)
        },{deep:false});// 一定会默认启动deep深度监视,配置是无效的
        return {counter,data};
    }
}
</script>

<style>

</style>

<template>

    <h1>{ { counter }}</h1>

    <button @click="counter++">按一下</button>

    <h1>{ { data.a.b.c.counter }}</h1>

    <button @click="data.a.b.c.counter++">按一下</button>

</template>

<script>

import {watch,ref} from "vue";

export default {

    name : "App",

    setup(){

        let counter = ref(1);

        let data = ref({

            a : {

                b : {

                    c : {

                        counter : 1

                    }

                }

            }

        });

        // 错误的,因为获取的是一个值

        // watch(counter.value,(newValue,oldValue)=>{

           

        // });

        // 可以监视到,效果和reactive是一样的,因为这里都是一个Proxy对象

        watch(()=>counter.value,(newValue,oldValue)=>{

            console.log(newValue,oldValue)

        });

        // 直接放进去,默认是没有开启深度监视的

        watch(data,(newValue,oldValue)=>{

            console.log(newValue,oldValue)

        },{immediate:true,immediate:true});

        // 这种可以监视到,因为底层还是Proxy对象

        // 不需要箭头函数去指

        // ref下如果包裹的是一个对象,而且watch没有指向value那个Proxy,而是指向对象本身,就不会开启深度监视

        watch(data.value,(newValue,oldValue)=>{

            console.log(newValue,oldValue)

        },{deep:false});// 一定会默认启动deep深度监视,配置是无效的

        return {counter,data};

    }

}

</script>

<style>

</style>

猜你喜欢

转载自blog.csdn.net/2201_75960169/article/details/135221961