vue watch deep 用法

发布时间 2023-06-14 13:17:00作者: 盘思动

简单案例

<template>
    <div>
        <h1>watch deep</h1>
        <p>obj:{{obj}}</p>
        <p>调用watch次数:{{times}}</p>
        <button @click="chgObj">改变对象</button>
    </div>
</template>
<script>
export default {
    data(){
        return {
            obj:{
                name:'张三',
                age:19
            },
            times:0
        }
    },
    created(){

    },
    methods:{
        chgObj(){
            this.obj.age++;// 修改对象内部属性,如果没有deep不会处罚回调函数
            // this.obj = {// 修改整个对象,没有deep设置,也会触发watch
            //     name : "李四",
            //     age: 22
            // }
        }
    },
    watch:{
        obj:{
            handler(newVal,oldVal){
                console.log(`旧的:${JSON.stringify(oldVal)},新的:${JSON.stringify(newVal)}`);
                this.times++;
            },
            deep:true
        }
    }
}
</script>