watch监控,对比新值和旧值做出相应判断

数据变化的监控经常使用,我们可以先来看一个简单的数据变化监控的例子。例如天气预报的穿衣指数,它主要是根据温度来进行提示的,当然还有其它的,咱们就不考虑了。

html

<div id="app">
         <span>今日温度{{message}}℃</span>
         <span>穿衣指数{{message2}}</span>
         <br />
         <br />
           <button @click="add">add</button>
           <button @click="decrease">decrease</button>
</div>

js

var suggestion=['T恤短袖','夹克长裙','棉衣羽绒服'];
        var vm = new Vue({
            el:"#app",
            data:{
                message:20,
                message2:"T恤短袖"
            },
             methods:{
            add:function(){
                this.message+=5
            },
            decrease:function(){
                this.message-=5
            }
           }
           // 有些时候我们会用实例属性的形式来写watch监控。也就是把我们watch卸载构造器的外部,这样的好处就是降低我们程序的耦合度,使程序变的灵活。
           // ,
           // watch:{
            //     message:function(newVal,oldVal){
            //         if(newVal>=26){
            //             this.message2=suggestion[0];
            //         }else if(newVal<26 && newVal >=0)
            //         {
            //             this.message2=suggestion[1];
            //         }else{
            //             this.message2=suggestion[2];
            //         }
            //     }
            // }
            
        })
        // 实例方法减少代码耦合度
        vm.$watch('message',function(newVal,oldVal){
                    if(newVal>=26){
                        this.message2=suggestion[0];
                    }else if(newVal<26 && newVal >=0){
                        this.message2=suggestion[1];
                    }else{
                        this.message2=suggestion[2];
                    }  
            })

 watch中把值赋值后 在mounted是获取不到的 这是有先后顺序的 mounted要先渲染  

监控嵌套内容

 inp: {
      isSelectDropdown: false
},  

watch: {
    inp: {
      deep: true,
      handler(val, oldVal) {
        console.log(val.isSelectDropdown);
      },
    }
  },
原文地址:https://www.cnblogs.com/Model-Zachary/p/6942092.html