57
Vue 3 學習之旅
響應式進階

Day 57: 觸發響應式更新:triggerRef

·6 分鐘閱讀·響應式進階

摘要

triggerRef 是一個可以手動強制觸發與一個「淺層 ref」(shallowRef) 相關聯的副作用(如畫面更新)的工具函數。

定義與說明

當你使用 shallowRef 時,修改其 .value 的內部屬性並不會觸發更新。如果你在某些情況下,確實需要手動通知 Vue 這個 shallowRef 的內容已經發生了深層變化,並希望它更新畫面,就可以呼叫 triggerRef

實作範例

Vue SFC
<script setup>
import { shallowRef, triggerRef } from 'vue';

const state = shallowRef({ nested: { count: 0 } });

function mutateDeepAndTrigger() {
  // 修改深層屬性
  state.value.nested.count++;
  
  // 手動觸發與 state 這個 shallowRef 相關的所有更新
  triggerRef(state);
}
</script>

<template>
  <p>Count: {{ state.nested.count }}</p>
  <button @click="mutateDeepAndTrigger">修改並手動觸發</button>
</template>

結論

triggerRef 是與 shallowRef 配套使用的命令式工具。它為我們提供了一種在淺層響應式場景下,手動控制深層變更通知的手段。

triggerRef shallowRef 手動觸發