深度监视:
Vue中的watch默认不监视对象内部值的改变(一层)
配置deep.true可以监测对象内部值改变(多层)
备注:
Vue自身可以监测对象内部值的改变,但Vue提供的watch默认不可以
使用watch时根据数据的具体结构,决定是否采用深度监视
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>天气案例_深度监视</title>
<!-- 引入Vue -->
<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<!-- 准备一个容器 -->
<div id="root">
<h2>今天天气很{{info}}</h2>
<button @click="changeweather">切换天气</button>
<hr/>
<h3>a的值是{{numbers.a}}</h3>
<button @click="numbers.a++">点我让a+1</button>
<hr/>
<h3>b的值是{{numbers.b}}</h3>
<button @click="numbers.b++">点我让b+1</button>
</div>
<script type="text/javascript">
Vue.config.productionTip=false
new Vue({
el:'#root',
data:{
ishot:true,
numbers:{
a:1,
b:2
}
},
computed:{
info(){
return this.ishot?'hot':'cool'
}
},
methods:{
changeweather(){
this.ishot=!this.ishot
},
},
watch:{
// 计算属性也可以被监视
ishot:{
// handler当ishot发生改变时调用
handler(newValue,oldValue){
console.log('ishot被调用了',newValue,oldValue)
}
},
// 监视多级结构中某个属性的变化,必须加引号,因为这个地方写的应该是字符串
'numbers.a':{
handler(){
console.log('a变化了')
}
},
// 监视多级结构中所有属性的变
numbers:{
deep:true,
handler(){
console.log('numbers change')
}
}
}
})
</script>
</body>
</html>