Vue 监视属性
监视属性
1、监视对象:普通属性、计算属性
2、当监视对象发生变化时,watch中的handler函数自动调用
3、常用属性
immediate:true 立刻执行,无论监视对象发没发生变化
depp: true 深度属性监视,一般只监视一层
4、两种写法
new Vue 传入 watch
watch:{
isHot:{
deep:true,
immediate:true,
handler(newVlaue, oldValue){
console.log("监视", newVlaue, oldValue)
}
}
}
通过vm.$watch(监视的对象,{handler方法})
vm.$watch("isHot",{
handler(newVlaue, oldValue){
console.log("监视", newVlaue, oldValue)
}
})
4、简写
不使用immediate和deep时
watch:{
//只用handler方法
isHot(newValue, oldValue){
console.log("监视", newValue, oldValue)
}
}
vm.$watch("isHot",function(newValue, oldValue){
console.log("正在监视", newValue, oldValue)
})
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>监视属性</title> <script type="text/javascript" src="../js/vue.js"></script> </head> <body> <div id="container"> <h2>今天天气很{{info}}</h2> <button @click="changeWeather">点击切换</button> </div> <script type="text/javascript"> const vm = new Vue({ el:"#container", data:{ isHot: true, }, computed:{ // 只用到get 简写 info(){ return this.isHot ? "炎热":"凉爽" } }, methods: { changeWeather(){ return this.isHot = ! this.isHot } }, /* watch:{ //只用handler方法 isHot(newValue, oldValue){ console.log("监视", newValue, oldValue) } } */ }) vm.$watch("isHot",function(newValue, oldValue){ console.log("正在监视", newValue, oldValue) }) </script> </body> </html>
5、computed和watch的区别
a、能被computed实现的函数,都能被watch实现,能被watch实现的,不一定能别computed实现,异步操作
b、被Vue管理的函数,写成普通函数;不被Vue管理的函数写成箭头函数(定时器回调函数、ajax回调函数、Promise回调函数)

浙公网安备 33010602011771号