vue监视之深度监视

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script type="text/javascript" src="../js/vue.js"></script>

    <title>监视属性深度监视</title>
</head>
<body>
    <!-- vue中的watch 默认不监视对象属性中的内部值的改变
        配置deep:true可以监视对象内部值的改变(多层)

        备注:
            vue自身可以检测对象内部值改变,但是vue提供的watch默认不可以
            使用watch需要根据对象的结构决定是否采用深度监视

    -->
    <div id="root">
        <h1>今天天气{{inFo}}</h1>
        <!-- 绑定事件的时候,事件 @xxx="yyy",yyy可以写一些简单的语句 -->
        <!-- <button @click="isHot=!isHot">切换天气</button> -->
        <button @click="chang">切换天气</button
            ><br>
        <h1>a的值是{{numbers.a}}</h1>    
        <button @click="numbers.a++">点我a+1</button>
            <br>
        <h1>b的值是{{numbers.b}}</h1>
        <button @click="numbers.b++">点我b+1</button>

    </div>
    <script>
        const vm=new Vue({
            el:"#root",
            data:{
                isHot:true,
                numbers:{
                    a:1,
                    b:1
                }

            },
            methods: {
                chang(){
                    this.isHot=!this.isHot;
                }
            },
            computed:{
                inFo(){
                    return this.isHot ? '炎热' : '凉爽';
                }
            },
            watch:{
                isHot:{
                    // immediate:true,//初始化时让handler调用一下
                    //handler在isHot发生改变时触发
                    handler(newValue,oldValue){
                        console.log(newValue,oldValue)
                    }
                },
                /* //监视多级结构中某个属性的变化
                "numbers.a":{
                    handler(){

                    }
                } */
                //监视多级结构中所有属性的变化
                numbers:{
                    deep:true,
                    handler(){

                    }
                }

            }

        })

        // vm.$watch("isHot",{
        //       // immediate:true,//初始化时让handler调用一下
        //     //handler在isHot发生改变时触发
        //     handler(newValue, oldValue) {
        //         console.log(newValue, oldValue)
        //     }
        // })
    </script>
</body>
</html>

 

posted @ 2022-10-31 10:21  小白字太白  阅读(265)  评论(0编辑  收藏  举报