Vue3中watch函数的使用

98 阅读1分钟
watch(x,y,z)

x:第一个参数是监视的数据,
y:第二个参数的监视的回调函数,
z:可选,第三个参数是监视的配置{immediate:true,deep:true}

一.watch监视ref定义的数据

const count=ref(1);
watch(count,(newValue, oldValue)=>{
  console.log(newValue, oldValue)
})

监听ref定义的数据,第一个参数是变量形式的

二.监听reactive定义的响应式对象

const state=reactive({
  count:1
})
watch(()=>state.count,(newValue, oldValue)=>{})

监听reactive定义的响应式对象时,第一个参数是函数形式的,即将需要监听的数据以函数的形式返回

三.监听多个参数

const name=ref("张三");
const state=reactive({
  count:1
})
watch([() =>state.count, name], ([newCount,newName], [preCount,preName]) => { });