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回调函数)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~