写在Vue对象的watch
中,它的值是配置对象——即属性名
当被监听的属性改变时,回调函数自动调用,进行相关操作
监视的属性必须存在,才能进行监视
监视的两种写法:
可传递参数:newValue、oldValue(参数名可以自定义),但是第一个是修改后的属性值,第二个是原先的属性值
var vm = new Vue({
el: "#root",
data: {
isHot: true
},
methods: {
changeWeather() {
this.isHot = !this.isHot
}
},
computed: {
info() {
if (this.isHot) {
return "炎热"
} else {
return "寒冷"
}
}
},
watch: {
isHot:{
handler(a, b){
console.log(a+"\n"+b)
}
}
}
})
输出结果:
false
true
handler方法的调用场景:当监视的属性发生改变时调用
上面的watch的特点是,最初绑定时不会执行
,等到 firstName 改变时
才执行监听计算。如果想要一开始就让他最初绑定的时候就执行改怎么办呢?
我们需要修改一下我们的 watch 写法,修改过后的 watch 代码如下:
var vm = new Vue({
el: "#root",
data: {
isHot: true
},
methods: {
changeWeather() {
this.isHot = !this.isHot
}
},
computed: {
info() {
if (this.isHot) {
return "炎热"
} else {
return "寒冷"
}
}
},
watch: {
isHot:{
immediate:true
handler(a, b){
console.log(a+"\n"+b)
}
}
}
})
immediate:true
代表如果在 watch 里声明了 firstName 之后
,会立即先执行里面的handler方法
,如果为 false就跟我们以前的效果一样,不会在绑定的时候就执行。
Vue对象.$watch("监听属性",{配置对象})
// vm为Vue对象
vm.$watch("isHot",{
immediate:true
handler(a, b){
console.log(a+"\n"+b)
}
})
Vue中的watch默认不监测对象内部值得改变
配置deep:true
可以监测对象内部值改变
备注:
监视data中对象的一个数据
监听的属性需要字符串形式,因为原本就是字符串的简写,但是此处特定要体现出来
var vm = new Vue({
el: "#root",
data: {
isHot: true,
numbers:{
a:1,
b:2
}
},
methods: {
changeWeather() {
this.isHot = !this.isHot
}
},
computed: {
info() {
if (this.isHot) {
return "炎热"
} else {
return "寒冷"
}
}
},
watch: {
"number.a":{
handler(){
console.log("1")
}
}
}
})
监视data中对象中的所有数据
var vm = new Vue({
el: "#root",
data: {
isHot: true,
numbers:{
a:1,
b:2
}
},
methods: {
changeWeather() {
this.isHot = !this.isHot
}
},
computed: {
info() {
if (this.isHot) {
return "炎热"
} else {
return "寒冷"
}
}
},
watch: {
number:{
deep:true,
handler(){
console.log("1")
}
}
}
})
前提:不需要immediate
和deep
属性,函数当作handler方法写
watch:{
isHot(){
....
}
}
或者
vm.$watch("isHot", function(){
...
})
两者的区别:
两个小原则: