所需工具:
JavaScript
聪明的大脑文章源自灵鲨社区-https://www.0s52.com/bcjc/javascriptjc/12364.html
勤劳的双手文章源自灵鲨社区-https://www.0s52.com/bcjc/javascriptjc/12364.html
文章源自灵鲨社区-https://www.0s52.com/bcjc/javascriptjc/12364.html
注意:本站只提供教程,不提供任何成品+工具+软件链接,仅限用于学习和研究,禁止商业用途,未经允许禁止转载/分享等文章源自灵鲨社区-https://www.0s52.com/bcjc/javascriptjc/12364.html
文章源自灵鲨社区-https://www.0s52.com/bcjc/javascriptjc/12364.html
教程如下
watch介绍
vue中watch用来监听数据的响应式变化.获取数据变化前后的值文章源自灵鲨社区-https://www.0s52.com/bcjc/javascriptjc/12364.html
watch的完整入参文章源自灵鲨社区-https://www.0s52.com/bcjc/javascriptjc/12364.html
[php]
watch(监听的数据,副作用函数,配置对象)
watch(data, (newData, oldData) => {}, {immediate: true, deep: true})
[/php]文章源自灵鲨社区-https://www.0s52.com/bcjc/javascriptjc/12364.html
watch监听的不同情况
创建响应式数据文章源自灵鲨社区-https://www.0s52.com/bcjc/javascriptjc/12364.html
[php]
import { ref, watch, reactive } from "vue";
let name = ref("moxun");
let age = ref(18);
let person = reactive({
Hobby: "photo",
city: {
jiangsu: {
nanjing: "雨花台",
},
},
});
[/php]文章源自灵鲨社区-https://www.0s52.com/bcjc/javascriptjc/12364.html
1 监听单个refimpl数据
[php]
watch(name, (newName, oldName) => {
console.log("newName", newName);
});
[/php]
2 监听多个refimpl数据
方式一:vue3允许多个watch监听器存在
[php]
watch(name, (newValue, oldValue) => {
console.log("new", newValue, "old", oldValue);
});
watch(age, (newValue, oldValue) => {
console.log("new", newValue, "old", oldValue);
});
[/php]
方式二:将需要监听的数据添加到数组
[php]
watch([name, age], (newValue, oldValue) => {
// 返回的数据是数组
console.log("new", newValue, "old", oldValue);
});
[/php]
3 监听proxy数据
注意
1.此时vue3将强制开启deep深度监听
2.当监听值为proxy对象时,oldValue值将出现异常,此时与newValue相同
[php]
// 监听proxy对象
watch(person, (newValue, oldValue) => {
console.log("newValue", newValue, "oldValue", oldValue);
});
[/php]
4 监听proxy数据的某个属性
需要将监听值写成函数返回形式,vue3无法直接监听对象的某个属性变化
[php]
watch(
() =& gt; person.Hobby,
(newValue, oldValue) => {
console.log("newValue",newValue, "oldvalue", oldValue);
}
);
[/php]
注意
当监听proxy对象的属性为复杂数据类型时,需要开启deep深度监听
[php]
watch(
() => person.city,
(newvalue, oldvalue) => {
console.log("person.city newvalue", newvalue, "oldvalue", oldvalue);
},{
deep: true
}
);
[/php]
5 监听proxy数据的某些属性
[php]
watch([() => person.age, () => person.name], (newValue, oldValue) => {
// 此时newValue为数组
console.log("person.age", newValue, oldValue);
});
[/php]
总结
1.与vue2中的watch配置一致
2.两个坑:
监听reactive定义的proxy代理数据时
oldValue无法正确获取
强制开启deep深度监听(无法关闭)
监听reactive定义的proxy代理对象某个属性时deep配置项生效
评论