vue之watch用法

tempalte:
<div id="demo">
        <p>{{arr[0]}}</p>
        <button @click="clickMe()">修改</button>
        //观察数据为字符串或数组
   <input v-model="example0"/>
</div>
script:
var vm = new Vue({
        el:"#demo",
        data:{
            example0:"",//监听对象为基本类型(字符串)
            obj:{
                name:"xiaoxia",
                age:"23"
            },
            arr:["xxx","zxw"]  //监听对象为引用类型(数组)
        },
         // 当对象发生变化时做一些操作
        watch:{
            //1.注意:当观察的数据为对象或数组时,curVal和oldVal是相等的,因为这两个形参指向的是同一个数据对象
            arr:{   
                deep:true,  //深度监听
                handler:function(newValue,oldValue){
                    console.log("newValue:");
                    console.log(newValue);
                    console.log("oldValue:");
                    console.log(oldValue);
                }
            },
            //2.观察的对象为基本类型时,新值为当前的值,旧值为改变之前的值
            example0(curVal,oldVal){
           console.log(curVal);
                console.log(oldVal);
           },
    },
methods:{
    clickMe:function(){
        //this.$set(this.arr,0,"xuxiaoxia")
        var arr2 = ["xuxiaoxia2","zhouxuewei2"];
        for(var i = 0;i<this.arr.length;i++){
            this.$set(this.arr,i,arr2);
        }
    }
}
})

原文地址:https://www.cnblogs.com/xuxiaoxia/p/9328262.html