vue3里watch和watchEffect的使用
1.在页面中引用watch
import {reactive,watch, ref} from 'vue'
2.在setup函数中使用watch监听ref定义的数据
//监听ref所定义的一个数据 newValue改变后新数据,变化前的旧数据 watch(sum,(newValue,oldValue)=>{ console.log('sum is changed',newValue,oldValue); },{immediate:true}) //immediate 立即执行
监听多个数据
//监听ref所定义的多个数据 watch([sum,msg],(newValue,oldValue)=>{ console.log('sum and msg is changed',newValue,oldValue); })
newValue和oldValue里数组的值和 [sum,msg] 的顺序是对应的
3.监听reactive所定义的响应式数据
姓名:{{person.name}}年龄:{{person.age}}薪水:{{person.job.j1.salary}}k
watchEffect
//不用指明监视的某个属性,监视的回调中用到哪个属性,那就监视哪个属性 watchEffect(()=>{ const x1 = person.job.j1.salary const x2 = sum.value console.log(' watcheffet回调执行了',x1,x2); })
watchEffect有点像computed,
computed注重值(回调函数的返回值),所有必须要写返回值
wacthEffect更注重过程(回调函数的函数体),所以不用写返回值,只要函数体内某个属性发生了变化,就重新走一遍流程。