? ? ? ?Vue偵聽器是根據組件狀態做DOM更新或者異步更新其他級聯狀態的。計算屬性的主要目標是根據已有數據計算出組件的狀態,它是組件內部的計算,計算結果在組件內部應用。偵聽器的主要目標是根據組件狀態的變動,做級聯的或者異步的操作或DOM更新,操作的影響范圍比計算屬性大得多。
<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.countwatch(()=>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 objwatch(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>
偵聽器的標準格式如下:
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 immediatelydeep:true, //default value is false, true value means watch is a deep watchflush:"post" //default value is "pre", "post" means watch callback function can fetch data after Vue DOM updated completely});
偵聽器默認情況下是懶執行、淺層偵聽、在Vue組件更新之前被調用的。