- 該文章是在學習 小滿vue3 課程的隨堂記錄
- 示例均采用
<script setup>
,且包含typescript
的基礎用法
前言
Vue3 中新增了一種特殊的監聽器 watchEffect
,它的類型是:
function watchEffect(effect: (onCleanup: OnCleanup) => void,options?: WatchEffectOptions
): StopHandle
下面通過實例來理解下它的用法
一、簡單使用
- 第一個參數就是要運行的
副作用函數 effect
- 函數內
用到哪些數據
才會監聽哪些數據
- 且會
立刻執行一次
(immediate)
<input type="text" v-model="message1" />
<br />
<input type="text" v-model="message2" />
<br />
import { ref, watchEffect } from "vue";const message1 = ref<string>("飛機");
const message2 = ref<string>("火車");watchEffect(() => {console.log("message1========>,", message1);// 不使用 message2 就不會監聽 message2// console.log("message2========>,", message2);
});
二、副作用 effect 的參數
- effect 的參數 也是一個
函數
,用來注冊清理回調
。 清理回調
會在該副作用下一次執行前被調用
,可以用來清理無效的副作用,例如等待中的異步請求
<input type="text" v-model="message1" />
<br />
<input type="text" v-model="message2" />
<br />
import { ref, watchEffect } from "vue";const message1 = ref<string>("飛機");
const message2 = ref<string>("火車");watchEffect((onCleanup) => {console.log("message11111========>,", message1);console.log("message22222========>,", message2);onCleanup(() => {console.log("onCleanup —————— 下一次運行之前要做的事");});
});
頁面刷新,首次打印:
更改輸入框的值,再次打印:
三、watchEffect 返回值
- 返回值是一個用來
停止偵聽器
的函數,調用后不再偵聽 - 需要注意的是:停止時,
不影響最后一次 onCleanup 的執行
<input type="text" v-model="message1" />
<br />
<input type="text" v-model="message2" />
<br />
<button @click="stopWatch">停止watchEffect</button>
const stop = watchEffect((onCleanup) => {console.log("message11111========>,", message1);console.log("message22222========>,", message2);onCleanup(() => {console.log("onCleanup —————— 下一次運行之前要做的事");});
});const stopWatch = () => {stop();
};
頁面刷新,首次打印:
更改輸入框的值,再次打印:
點擊按鈕 停止偵聽,再次打印:
四、options配置
watchEffect 的第二個參數是配置項:
flush
:watch 的執行順序pre
|post
|sync
,默認:pre
,具體含義可以看上一篇 watch 中的解釋- 一般需要在 dom 更新之后再獲取的情況,可以設置為
post
onTrack
用于開發環境調試onTrigger
用于開發環境調試
<input id="ipt" v-model="iptVal" />
const iptVal = ref<string>("aa");watchEffect(() => {// 測試 flushconst spanEle = document.getElementById("ipt");// flush = pre 時,打印 null; flush = post 時,打印節點console.log("spanEle========>,", spanEle); // 修改 iptVal 測試 onTrack、onTriggerconsole.log("iptVal============>", iptVal.value);},{flush: "post",// 收集依賴時觸發onTrack: () => {debugger;},// 更新時觸發onTrigger: () => {debugger;},}
);
五、周邊 api
watchPostEffect()
:watchEffect()
使用flush: 'post'
選項時的別名watchSyncEffect()
:watchEffect()
使用flush: 'sync'
選項時的別名