1. 场景引入
在实际开发中,有时开发者需要根据某个属性的变化,做出相应的决策,因此Vue 为开发者提供了watch .这一监视属性,用于实现此类需求。比如下面这个场景,开发者要监测天气的变化,每次点击切换天气,就会变化,要求我们对不同的天气做出不同的处理。


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<div id="root">
<h2>今天天气很{{info}}</h2>
<button @click="changeWeather">切换天气</button>
</div>
</body>
<script>
Vue.config.productionTip = false;
const vm = new Vue({
el:'#root',
data:{
isHot:true,
},
computed:{
info(){
return this.isHot ? '炎热':'寒冷'
}
},
methods:{
changeWeather(){
this.isHot = !this.isHot
}
},
})
</script>
</html>
2. watch
我们在vm中加入watch属性,
监视属性中的函数,能够通过获取newValue和oldValue的值,进行监视到属性改变后的一些操作;
接收两个参数:
**newValue:**表示新的值
**oldValue:**表示改变前的值

watch:{
isHot:{
handler(newValue,oldValue){
console.log("天气被修改了"+newValue+oldValue);
}
}
我们再次尝试,控制台打印出了天气的变化

immediate属性
实现初始化的时候调用一次监视函数handler,默认为false
watch:{
isHot:{
immediate:true,
handler(newValue,oldValue){
console.log("天气被修改了"+newValue+oldValue);
}
}

同时watch存在第二种写法,在vm对象外面

3. 深度监视
watch 默认监视单层属性的改变,想实现监测多层结构需要使用deep 属性
监视多级结构中某个属性的变化 watch:{ “numbers.a”:{ … } } //numbers是data上的一个key,里面包含a
这里注意:本来所监视的属性都是字符串,需要带双引号,只不过单层的省略了双引号
deep 属性 用于开启深度监视,多级结构中任何一个属性值发生变化,都能够检测到(内部的改变也能够通过外部监测到),监视多级结构中所有属性的变化 
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<div id="root">
<h2>今天天气很{{info}}</h2>
<button @click="changeWeather">切换天气</button><hr/>
<button @click="numbers.a++">点我a++</button>
<h3>{{numbers.a}}</h3>
<button @click="numbers.b++">点我b++</button>
<h3>{{numbers.b}}</h3>
</div>
</body>
<script>
Vue.config.productionTip = false;
const vm = new Vue({
el:'#root',
data:{
isHot:true,
numbers:{
a:1,
b:1,
}
},
computed:{
info(){
return this.isHot ? '炎热':'寒冷'
}
},
methods:{
changeWeather(){
this.isHot = !this.isHot
}
},
watch:{
numbers:{
deep:true,
handler(){
console.log('numbers被修改');
}
}
}
})
</script>
</html>

可以看到,点击a或者b++的按钮是有被检测到的 
4. 监视属性简写
与计算属性类似,当不需要使用其他属性,只使用handler属性时,可以使用简写形式
isHot(newValue,oldValue){
console.log("天气被修改了"+newValue+oldValue);
}
函数写法:
vm.$watch('isHot',function(newValue,oldValue){
console.log("天气被修改了"+newValue+oldValue);
}
5. 小结
小结一下: 
|