一.为什么要用 watch
当某些数据一旦发生变化,我们就想要采取某种措施时使用
示例
当 price 一旦发生变化时,我们想要计算出 priceDifferences
<template>
<div class="watch">
<h2>{{price}}</h2>
<h2>{{priceDifferences}}</h2>
<button @click="addprice">price *2</button>
</div>
</template>
<script>
export default{
data(){
return{
priceDifferences:0,
price:100
}
},
watch:{
price:function(newVal,oldValue){
this.priceDifferences = newVal - oldValue
console.log(this.priceDifferences)
}
},
methods:{
addprice(){
this.price = this.price *2
}
}
}
</script>
二.watch的用法
1.普通监听(data 里的普通数据)
<template>
<div class="watch">
<div>{{msg}}</div>
<button @click="changemsg">changemsg</button>
</div>
</template>
<script>
export default{
data(){
return{
msg:'这是一个普通监听'
}
},
watch:{
msg:function(newval,oldval){
console.log('由',oldval,'到',newval)
}
},
methods:{
changemsg(){
this.msg = "嘿嘿嘿,是不是监听到了呢"
}
}
}
</script>
运行结果
点击前
点击后
控制台输出
2.监听数组
<template>
<div class="watch">
<div v-for="(a,aindex) in arr" :key="aindex">{{a}}</div>
<button @click="changearr">changearr</button>
</div>
</template>
<script>
export default{
data(){
return{
arr:[1,2,3]
}
},
watch:{
arr:{
handler:function(newVal){
console.log('arr newVal',newVal)
}
}
},
methods:{
changearr(){
this.arr = this.arr.reverse();
}
}
}
</script>
运行结果
点击前
点击后
控制台输出
3.监听对象
监听对象时有两种方法:
1)
obj:{
handler:function(newVal){
console.log('newVal',newVal)
},
deep:true
}
2)
'obj.course':function(newval,oldval){
console.log("这是第二种监测方法",newval)
}
完整的代码
<template>
<div class="watch">
<h1>{{obj.name}}</h1>
<h2>{{obj.age}}</h2>
<div>{{obj.sex}}</div>
<h3 v-for="(cou,couindex) in obj.course" :key="couindex">{{cou}}</h3>
<button @click="addAge">age ++</button>
<button @click="changeCourse">change course</button>
</div>
</template>
<script>
export default{
data(){
return{
obj:{
course:{
one:'chinese',
two:'english',
three:'math'
}
}
}
},
watch:{
//第一种方法
obj:{
handler:function(newVal){
console.log('newVal',newVal)
},
deep:true
},
//第二种方法
'obj.course':function(newval,oldval){
console.log("这是第二种监测方法",newval)
}
},
methods:{
changeCourse(){
this.obj.course = {
one:'语文',
two:'英语',
three:'数学'
}
}
}
}
</script>
运行结果
点击前
点击后
控制台输出
注意:当监听对象时 增加属性时监测不到,因为该属性没有在 data 里注册,不是响应式的
解决办法:Vue.set(object, key, value)或者vm.$set方法(全局 Vue.set 方法的别名)
<template>
<div class="watch">
<h1>{{obj.name}}</h1>
<h2>{{obj.age}}</h2>
<div>{{obj.sex}}</div>
<h3 v-for="(cou,couindex) in obj.course" :key="couindex">{{cou}}</h3>
<button @click="addsex">addsex</button>
</div>
</template>
<script>
export default{
data(){
return{
obj:{
name:'lily',
age:'23',
course:{
one:'chinese',
two:'english',
three:'math'
}
}
}
},
watch:{
obj:{
handler:function(newVal){
console.log('newVal',newVal)
},
deep:true
}
},
methods:{
addsex(){
//监测不到,控制台不会打印改变后的值
// this.obj.sex = "female"
//使用 $set 之后可以监测到值
this.$set(this.obj,'sex','female')
}
}
}
</script>
运行结果
点击前
点击后
控制台输出