Vue侦听器是根据组件状态做DOM更新或者异步更新其他级联状态的。计算属性的主要目标是根据已有数据计算出组件的状态,它是组件内部的计算,计算结果在组件内部应用。侦听器的主要目标是根据组件状态的变动,做级联的或者异步的操作或DOM更新,操作的影响范围比计算属性大得多。
javascript
<script setup lang="ts">
import {reactive, ref, watch} from "vue"
const obj=reactive({name:"obj",count:0});
// count is formal parameter, it's change will not saved to obj.count
watch(()=>obj.count,(count)=>{
count=count+3;
console.log("watch by obj.count by getter :"+count);
});
// obj is real parameter , it's change will be saved to obj
watch(obj,(oldValue,newValue)=>{
console.log("watch by obj by deep way :"+newValue.count);
});
watch(name,(oldName,newName)=>{
console.log("oldName is "+oldName+", newName is "+newName);
});
</script>
<template>
<div>
<button type="button" @click="obj.count++">测试侦听器</button>
</div>
</template>
<style>
</style>
侦听器的标准格式如下:
javascript
const data=ref({});
watch(data,(oldValue,newValue)=>{
console.log(oldValue);
console.log(newValue);
},{
immediate:true, //default value is false, true value means watch callback function will be called immediately
deep:true, //default value is false, true value means watch is a deep watch
flush:"post" //default value is "pre", "post" means watch callback function can fetch data after Vue DOM updated completely
});
侦听器默认情况下是懒执行、浅层侦听、在Vue组件更新之前被调用的。