flush選項(xiàng)表示回調(diào)函數(shù)調(diào)用的時(shí)機(jī),有三個(gè)值可以選擇
pre:默認(rèn)值,表示在dom更新前調(diào)用,比如這是你需要再改變其他數(shù)據(jù),就使用pre,這些數(shù)據(jù)改變完一起更新dom,提高性能
post:表示dom更新完成后調(diào)用,比如你要獲取dom或者子組件,跟我們之前使用nextTick的意思一樣
sync:同步調(diào)用
當(dāng)flush 為 post
當(dāng)你更改了響應(yīng)式狀態(tài),它可能會(huì)同時(shí)觸發(fā) Vue 組件更新和偵聽(tīng)器回調(diào)。
默認(rèn)情況下,用戶(hù)創(chuàng)建的偵聽(tīng)器回調(diào),都會(huì)在 Vue 組件更新之前被調(diào)用。這意味著你在偵聽(tīng)器回調(diào)中訪(fǎng)問(wèn)的 DOM 將是被 Vue 更新之前的狀態(tài)。
如果想在偵聽(tīng)器回調(diào)中能訪(fǎng)問(wèn)被 Vue 更新之后的DOM,你需要指明 flush: 'post'
<script lang="ts" setup>
const num = ref(1);
const numRef = ref<HTMLElement | null>(null);
watch(num, (news) =>{
console.log(news)
// 當(dāng)不加 {flush: 'post'} textContent等于 1
// 反之 textContent等于 2
console.log(numRef.value?.textContent, 'textContent')
},{flush: 'post'});
const onToggle = () =>{
num.value = 2;
}
</script>
<template>
<div ref="numRef" @click="onToggle">{{num}}</div>
</template>