
watch函数用来侦听特定的数据源,并在回调函数中执行副作用。默认情况是惰性的,也就是说仅在侦听的源数据变更时才执行回调。
watch(source,callback,[options])
参数说明:
source:可以支持string,Object,Function,Array;用于指定要侦听的响应式变量callback:执行的回调函数options:支持deep、immediate和flush选项侦听reactive定义的数据
import {defineComponent,ref,reactive,toRefs,watch} from "vue";
export default defineComponent({
setup(){
const state=reactive({nickname:"xiaofen",age:20});
setTimeout(()=>{
state.age++;
},1000);
//修改age值时会触发watch的回调
watch(
()=>state.age,(curAge,preAge)=>{
console.log("新值:",curAge,"老值:",preAge);
}
);
return{
...toRefs(state),
}
}
})
侦听ref定义的数据
const year=ref(0);
setTimeout(()=>{
year.value++;
},1000);
watch(year,(newVal,oldVal)=>{
console.log('新值:',newVal,"老值",oldVal);
})
侦听多个数据
上面两个例子中,我们分别使用了两个watch,当我们需要侦听多个数据源时,可以进行合并,同时侦听多个数据:
watch([()=>state.age,year],([curAge,newVal],[preAge,oldVal])=>{
console.log("新值:",curAge,"老值",preAge);console.log("新值",newVal,"老值",oldVal)});
侦听复杂的嵌套对象
在开发中,复杂数据随处可见,例如:
const state=reactive({
room:{
id:100,
attrs:{
size:"140平方米"
type:"三室两厅",
},
},
});
watch(
()=>state.room,(newType,oldType)=>{
console.log("新值:",newType,"老值:",oldType);
},
{deep:true}
)
如何不使用第三个参数deep:true,是无法监听到数据变化的
stop停止监听
我们在组件中创建的watch监听,会在组件被销毁时自动停止。如果在组件销毁之前我们想要停止某个监听,可以调用watch()函数的返回值, *** 作如下:
const stopWatchRoom = watch(()=>state.room,(newType,oldType)=>{
console.log("新值:",newType,"老值:",oldType)
},{deep:true});
setTimeout(()=>{
//停止监听
stopWatchRoom()
},3000)
还有一个监听函数watchEffect,在我看来watch已经能满足监听的需求,为什么还要有watchEffect呢?接下来对它进行介绍
import { defineComponent, ref, reactive, toRefs, watchEffect } from "vue";
export default defineComponent({
setup() {
const state = reactive({ nickname: "xiaofan", age: 20 });
let year = ref(0)
setInterval(() =>{
state.age++
year.value++
},1000)
watchEffect(() => {
console.log(state);
console.log(year);
}
);
return {
...toRefs(state)
}
},
});
执行结果首先打印一次state和year值;然后每隔一秒,打印state和year值。从上面的代码可以看出,并没有像watch一样需要先传入依赖,watchEffect会自动收集依赖,只要指定一个回调函数。在组件初始化时,会先执行一次来收集依赖,然后收集到的依赖中数据发生变化时,就会再次执行回调函数。所以对比如下:
watchEffect不需要手动传入依赖watchEffect会先执行一次用来自动收集依赖watchEffect无法获取到变化前的值,只能获取变化后的欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)