3. 监视属性

  • 当被监视的属性变化时,回调函数自动调用,进行相关操作
  • 监视的属性必须存在,才能进行监视
  • 监视的两种写法

    • new Vue是传入watch配置
    • 通过vm.$watch

3.1 在new Vue中的watch配置

<div id="root">
    <h1>今天的天气很{{isHot ? "炎热" : "凉爽"}}</h1>
    <h1>今天的天气很{{info}}</h1>
    <button @click="isHot=!isHot">切换天气</button>
</div>
new Vue({
    el:"#root",
    data:{
        isHot:true
    },
    computed:{
        info(){
            return this.isHot?"炎热":"凉爽";
        }
    },
    //监视data或者computed中的属性
    watch:{
        //监视data中的isHot属性
        isHot:{
            //newValue:新的值,oldValue:旧的值
            handler(newValue,oldValue){
                console.log(newValue, oldValue);
            }
        },
        //监视computed中的info计算属性
        info:{
            handler(newValue, oldValue) {
                console.log(newValue, oldValue);
            }
        }
    }
})

3.2 在vm原型中配置

const vm=new Vue({
    ...
})
vm.$watch("info",{
    handler(newValue, oldValue) {
        console.log(newValue, oldValue);
    }
})

3.3 深度监视

  • Vue中的watch默认不监测对象内部值的改变(一层)
  • 配置depp:true可以监测对象内部值改变(多层)
  • 备注

    • Vue自身可以监测对象内部值的改变,但Vue提供的watch默认不可以!
    • 使用watch时根据数据的具体结构,决定是否采用深度监视

3.3.1 监视对象中的某个属性

<div id="root">
    <div>{{number.a}}</div>
    <button @click="number.a++">点我number.a+1</button>
    <div>{{number.b}}</div>
    <button @click="number.b++">点我number.b+1</button>
</div>
<script>
    const vm=new Vue({
        el:"#root",
        data:{
            number:{
                a:1,
                b:1
            }
        },
        watch:{
            "number.a":{
                handler(newValue,oldValue){
                    console.log("number.a被改变了! "+newValue, oldValue);
                }
            },
            "number.b":{
                handler(newValue,oldValue){
                    console.log("number.b被改变了! "+newValue, oldValue);
                }
            },
        }
    })
</script>

3.3.2 深度监视

watch:{
    number:{
        //打开深度监视
        deep:true,
            handler(newValue,oldValue){
            console.log("number被改变了! "+newValue, oldValue);
        }
    }
}

3.3.3 监视属性简写

  • 在Vue配置中
<div id="root">
    <h1>今天的天气很{{isHot ? "炎热" : "凉爽"}}</h1>
    <button @click="isHot=!isHot">切换天气</button>
</div>
<script>
    new Vue({
    el:"#root",
    data:{
        isHot:true,
    },
    watch:{
        //简写方式不能有其他配置项,比如immediate,deep配置项
        //简写方式
        isHot(newValue,oldValue){
            console.log("监视:",newValue, oldValue);
        }
    }
});
</script>
  • 在Vue原型中

    const vm =new Vue({
        ....
    });
    //注意这里必须要使用function函数,不能使用箭头函数,否则this为Windows对象
    vm.$watch("isHot",function (){
        console.log("监视:",newValue, oldValue);
    });
最后修改:2023 年 01 月 31 日
如果觉得我的文章对你有用,请随意赞赏