watch : 监听属性,只能监听data中已存在的数据
在监听的数据变化时,进行某些操作
1.默认监听:只能监听简单数据类型
new Vue({
el: '#app',
data: {
bool: true,
name: '张三',
friends: ['张三', '李四', '王五']
},
methods: {
tab() {
this.bool = !this.bool;
this.name = '哈哈哈';
}
},
watch: {
// 两个参数,第一个参数是新值,第二个参数是旧值(可以省略)
// 当bool中的参数发生变化是,里面的代码生效
bool(val){
// a.通过判断来改变值,此时监听的是函数
console.log(val);
}
}
})
2.深度监听:监听复杂数据类型(对象)
new Vue({
el: '#app',
data: {
bool: true,
name: '张三',
friends: ['张三', '李四', '王五']
},
methods: {
tab() {
this.bool = !this.bool;
this.name = '哈哈哈';
}
},
watch: {
//深度监听(因为普通的监听只能监听到简单数据类型,所以需要深度监听来监听复杂数据类型)
friends: {
deep: true,
handler(val) {
console.log(val);
}
}
}
})
3.页面加载时自动监听,此时监听的是对像
new Vue({
el: '#app',
data: {
bool: true,
name: '张三',
friends: ['张三', '李四', '王五']
},
methods: {
tab() {
this.bool = !this.bool;
this.name = '哈哈哈';
}
},
watch: {
bool(val){
// 页面加载时自动执行,此时监听的是对象
immediate:true,
handler(val){
console.log(val);
}
},
}
})