网页网站自做全搞定,江西省赣州市定南县,中建国际建设有限公司官网是央企吗,傻瓜式建网站vue中$watch()和watch属性都是监听值的变化的#xff0c;是同一个作用#xff0c;但是有两个不同写法。 用法一#xff1a;
//注意#xff1a;这种方法是监听不到对象的变化的。
this.$watch((newVal,oldVal){ })
用法二#xff1a;
watch:{xxx:(newVal,oldVal)是同一个作用但是有两个不同写法。 用法一
//注意这种方法是监听不到对象的变化的。
this.$watch((newVal,oldVal){ })
用法二
watch:{xxx:(newVal,oldVal){ // xxx是data里的数据}// 写法二对象方法的简写// xxx(newVal,oldVal){ // xxx是data里的数据// }
}//监听对象某个值的变化
watch:{xxx.value:newVal,oldVal){ // xxx.value是data里对象的value}// 写法二对象方法的简写// xxx.value(newVal,oldVal){ // xxx.value是data里对象的value// }
}
举个栗子
templatediv input typetext v-modelname{{name}}input typetext v-modelage{{age}}input typetext v-modelobj.id{{obj.id}}input typetext v-modelobj{{obj}}/div
/template
scriptexport default {name: Home,data() {return {name: ,age: ,obj: {id: 1,addr: gz}};},created() {this.obj {id: 99,addr: gd}// 用法一 this.$watch(要监听的值,(oldVal,newVal){ })this.$watch(name, (newValue, oldValue) {console.log(newValue _新值);console.log(oldValue _旧值);});//这样监听不到对象的变化的this.$watch(obj, (newval, oldval) {console.log(newval);console.log(oldval);});},//用法二watch: {age: (newValue, oldValue) {console.log(newValue);console.log(oldValue);},// 监听对象中的某个属性的变化obj.id: (newVal, oldVal) {console.log(newVal);console.log(oldVal);},//深度监听obj: {handler(newVal, oldVal) {console.log(newVal);console.log(oldVal);},//开启深度监听deep: true,//页面初始化立即执行immediate: true}},};
/script
style langcss scoped
/style
☀ 参考资料
浅谈Vue中监听属性—watch监听器的使用方法
vue - watch:{}监听与 this.$watch()的区别 | this.$watch 和组件的 watch 有什么区别