vue3中的watch的用法和几种常见情况
vue3中的watch的用法和几种常见情况
·
vue3中的watch是一个组合式的API使用时需要引入
watch函数收三个参数:
-
需要进行监听的数据的数组,
-
监听的数据发生改变时的回调
-
配置项
-
情况一(监视一个数字的变化)
let count = ref(0) watch(count,(newV,oldV)=>{ console.log(newV,oldV); })
-
情况二(监听俩个数据的变化)
let year = ref(2000) let age = ref(22) function count(){ year.value++ age.value++ } watch([year,age],(newV,oldV)=>{ console.log(newV,oldV); })
-
加入配置项参数
let year = ref(2000) let age = ref(22) function count(){ year.value++ age.value++ } watch([year,age],(newV,oldV)=>{ console.log(newV,oldV); },{immediate:true}) //设置立即监听
会立即监听一次
-
情况三(监听reactive管理的对象的变化)
const student = reactive({ name:'张三', age:20, a:{ b:{ salary:'20k' } } }) function changeName(){ student.name = student.name + '@' } function changeAge(){ student.age ++ } function changeSalary(){ student.a.b.salary = "50k" } watch(student,(newV,oldV)=>{ console.log(newV,oldV); })
注意:此时的oldValue失效,在监听深层次的数据时依旧可以监听到变化,可以看出vue3默认开启了深度监视
-
情况4(监听对象中的某个属性)
//上方代码watch改写为 watch(()=>student.name,(newValue,oldValue)=>{ console.log(newValue,oldValue); })
监听对象的某个属性需要将watch函数的第一个参数写为一个函数需要监听的属性作为返回值,可以正确的获得oldValue
-
情况5(监听对象的某些属性)
//watch改写为 watch([()=>student.name,()=>student.age],(newValue,oldValue)=>{ console.log(newValue,oldValue); })
监听对象的一些属性传入的第一个参数是存放返回对象属性的函数的数组,oldValue有效
-
情况6(监听对象套很深的对象的属性)
const student = reactive({ a: { b: { salary: "20k", }, }, }); function changeSalary() { student.a.b.salary = "50k"; } watch( () => student.a, (newValue, oldValue) => { console.log(newValue, oldValue); }, { deep: true } );
监听对象嵌套很深需要开启深度监听,oldValue不好使
更多推荐
已为社区贡献1条内容
所有评论(0)