watch
watch的API完全等同于组件watch选项的Property :watch需要侦听特定的数据源,并在回调函数中执行副作用;默认情况下它是惰性的,只有当被侦听的源发生变化时才会执行回调;
与watchEffect的比较,watch允许我们∶懒执行副作用(第一次不会直接执行);更具体的说明当哪些状态发生变化时,触发侦听器的执行;口访问侦听状态变化前后的值;
基本使用
watch方法的第一个参数是要监听的数据,可以是ref对象、reactive对象、数组、getter方法,第二个参数是数据改变时的回调,第三个参数时options
<script>
import { ref, reactive, watch} from "vue";
export default {
setup() {
const info =reactive({
name: "sk",
age:19
});
// 侦听watch是,传入一个getter函数
// watch(()=>info.name,(newValue,oldValue)=>{
// console.log("newValue",newValue,"oldValue",oldValue);;
// });
// 传入可响应式对象:reactive对象/ref对象
// reactive对象获取到的newValue和oldValue都是reactive对象
// watch(info,(newValue,oldValue)=>{
// console.log("newValue",newValue,"oldValue",oldValue);;
// });
// 如果希望newValue和oldValue是一个普通的对象
watch(()=>{
return {...info};
},(newValue,oldValue)=>{
console.log("newValue",newValue,"oldValue",oldValue);;
});
// ref对象获取到的newValue和oldValue都是值的本身
const name = ref("sk");
watch(name,(newValue,oldValue)=>{
console.log("newValue",newValue,"oldValue",oldValue);;
});
const changeData=()=>{
info.name="shopkeeper";
// name.value="shopkeeper";
}
return{
changeData,
info,
}
}
}
</script>
watch侦听多个数据源
<script>
import { ref, reactive, watch} from "vue";
export default {
setup() {
// 定义响应式对象
const info =reactive({
name: "sk",
age:19
});
const name = ref("sk");
// 侦听多个数据源
watch([()=>{
return {...info}
},name],([newInfo,newName],[oldInfo,oldName])=>{
console.log(newInfo,newName,oldInfo,oldName);
});
const changeData=()=>{
info.name="shopkeeper";
// name.value="shopkeeper";
}
return{
changeData,
info,
}
}
}
</script>
watch的选项
和options中的watch一样:
<script>
import { ref, reactive, watch} from "vue";
export default {
setup() {
// 定义响应式对象
const info =reactive({
name: "sk",
age:19,
friend:{
name:"kobe"
}
});
// 源码中,传入reactive会默认开启deep侦听,而传入getter方法不会
watch([()=>{
return {...info}
}],(newInfo,oldInfo)=>{
console.log(newInfo,oldInfo);
},{
deep:true,
immediate:true
});
const changeData=()=>{
info.friend.name="james";
}
return{
changeData,
info,
}
}
}
</script>