在vue中如果想知道一个值是否发生改变就得用到侦听器watch
第一种用法 如果在vue创建实例是很明确监视谁
<body>
<div id='root'>
<h2 :class= really ? 'Color:"yellow"' : 'Color:"block"'>字体颜色是{{really}}色</h2>
<button @click = 'changeColor'>切换字体颜色</button>
</div>
</body>
<script>
const vm = new vue({
el:'#root',
data:{
really:false
},
methods:{
changeColor(){
this.really = !this.really
}
},
watch:{
really:{
immediate:true, //无论值是否发生改变,时刻都会监听 默认值为false
//handler什么时候调用 当really发生改变时
handler(newValue,oldValue){
console.log('really 发生了改变',newValue,oldValue) //输出 really 发生了改变 true false
}
}
}
})
</script>
第二种用法 如果在vue创建实例是不明确去监视谁
<body>
<div id='root'>
<h2 :class= really ? 'Color:"yellow"' : 'Color:"block"'>字体颜色是{{really}}色</h2>
<button @click = 'changeColor'>切换字体颜色</button>
</div>
</body>
<script>
const vm = new vue({
el:'#root',
data:{
really:false
},
methods:{
changeColor(){
this.really = !this.really
}
},
})
vm.$watch('really',{
immediate:true, //无论值是否发生改变,时刻都会监听 默认值为false
//handler什么时候调用 当really发生改变时
handler(newValue,oldValue){
console.log('really 发生了改变',newValue,oldValue) //输出 really 发生了改变 true false
})
</script>
深度监视
<body>
<div id='root'>
<h2>a的值是:{{number.a}}</h2>
<button @click = 'number.a++'>a+1</button>
</div>
</body>
<script>
const vm = new vue({
el:'#root',
data:{
number:{
a:0,
b:0,
}
},
watch:{
number:{
deep:true,
immediate:true, //无论值是否发生改变,时刻都会监听 默认值为false
//handler什么时候调用 当really发生改变时
handler(newValue,oldValue){
console.log('really 发生了改变',newValue,oldValue) //输出 really 发生了改变 true false
}
}
}
})
</script>