美文网首页
vue 监听器

vue 监听器

作者: 程序猿的小生活 | 来源:发表于2022-06-13 14:56 被阅读0次
<html>
    <head>
         <script src="https://unpkg.com/vue@next"></script>
        <meta charset="utf-8">
        <title>检测</title>
    </head>
    <body>
        <div id="app" >
        <button @click="change">{{watchone}}</button>
        <button @click="change1">json深度检测{{this.json.a}}</button>
        <button @click="change2">数组深度检测{{this.arr}}</button>
        
        </div>
    </body>
    <script>
        Vue.createApp({
            data(){
                return{
                    watchone:"只是浅检测",
                    json:{
                        a:"1"
                    },
                    arr:["2","3"]
                    
                }

            },
            methods: {
                change() {
                    this.watchone = "改变了";
                },
                change1() {
                    this.json.a="5";
                },
                change2() {
                    this.arr.push("100");
                }
            },
            watch: {
                //浅度检测只检测属性值改变newValue新值  oldValue老值
                watchone(newValue, oldValue) {
                    console.log(newValue+oldValue);
                },
                /* json(){//这种写法无法去检测
                    alert("不会改变")
                } ,*/
                //深度检测 检测json变化
                json:{
                    handler(){
                        alert("不会改变")
                    },
                    deep:true
                },
                /* arr(){//这种写法不起作用
                    alert("数组改变")
                } */
                
                arr:{
                handler(){
                    alert("数组改变")
                },
                deep:true,//深度检测默认为false
                immediate:true//立即执行初始化时会走一遍默认为false
                },
                //总结:检测数组和json改变只能使用深度检测
            },
            
            
            
        }).mount("#app");
        
        
        
    </script>
</html>

相关文章

网友评论

      本文标题:vue 监听器

      本文链接:https://www.haomeiwen.com/subject/uiuomrtx.html