监视属性:watch

154 阅读1分钟

在项目当中经常能用到watch属性,今天我们就好好聊一聊,watch属性在什么时候用; 用了它,有什么好处?

  • 监视属性就是监视某一个属性的变化;
  • 我感觉,使用监视属性,就是能够获取监视的值;

不使用watch的代码

  • 不使用watch看起来,有点麻烦
<!--准备好一个容器-->
<h2>今天天气很{{info}}</h2>
<!--<button @click="isHot = !isHot">切换天气</button>-->
<button @click="changeWeather">切换天气</button>
data:{
isHot:true,
}
computed:{
info(){
return this.isHot ? '炎热' : '凉爽'
}
},
methods: {
changeWeather(){}
this.isHot = !this.isHot
}

使用监视属性watch

  • 监视谁:isHot
  • 怎么监视:handler()函数
  • 什么时候调用handler()?当isHot发生改变时,handler(){console.log('isHot被修改了')}
  • 穿参数,(newvalue,oldvalue)还能把修改前后的值获取到;
watch:{
isHot:{
immediate:true,//初始化时让handler调用一下
deep : true,//深度监视
handler(newValue,oldValue){
  console.log('isHot被修改了',newValue,oldValue)
  }
  }
}

watch还有另一种写法

vue.$watch('isHot',{
immediate:true,
handler(newValue,oldValue){
  console.log('isHot被修改了',newValue,oldValue)
  }
})

深度监视

deep : true,可以监测内部;

简写

watch:{
//正常写法
isHot:{
immediate:true,//初始化时让handler调用一下
deep : true,//深度监视
handler(newValue,oldValue){
  console.log('isHot被修改了',newValue,oldValue)
    }
},
//简写
isHot(newValue,oldValue){
 console.log('isHot被修改了',newValue,oldValue)
}

另一种写法的简写

vue.$watch('isHot',{
immediate:true,
handler(newValue,oldValue){
  console.log('isHot被修改了',newValue,oldValue)
  }
})
//简写
vue.$watch('isHot',function(newValue,oldValue){
  console.log('isHot被修改了',newValue,oldValue)
  }
})