當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Vue.js watchEffect()用法及代碼示例

立即運行一個函數,同時響應地跟蹤它的依賴關係,並在依賴關係發生變化時重新運行它。

類型

function watchEffect(
  effect: (onCleanup: OnCleanup) => void,
  options?: WatchEffectOptions
): StopHandle

type OnCleanup = (cleanupFn: () => void) => void

interface WatchEffectOptions {
  flush?: 'pre' | 'post' | 'sync' // default: 'pre'
  onTrack?: (event: DebuggerEvent) => void
  onTrigger?: (event: DebuggerEvent) => void
}

type StopHandle = () => void

細節

第一個參數是要運行的效果函數。效果函數接收可用於注冊清理回調的函數。清理回調將在下一次重新運行效果之前調用,可用於清理無效的副作用,例如待處理的異步請求(參見下麵的示例)。

第二個參數是一個可選的選項對象,可用於調整效果的刷新時間或調試效果的依賴關係。

返回值是一個句柄函數,可以調用它來阻止效果再次運行。

示例

const count = ref(0)

watchEffect(() => console.log(count.value))
// -> logs 0

count.value++
// -> logs 1

副作用清理:

watchEffect(async (onCleanup) => {
  const { response, cancel } = doAsyncWork(id.value)
  // `cancel` will be called if `id` changes
  // so that previous pending request will be cancelled
  // if not yet completed
  onCleanup(cancel)
  data.value = await response
})

停止觀察者:

const stop = watchEffect(() => {})

// when the watcher is no longer needed:
stop()

選項:

watchEffect(() => {}, {
  flush: 'post',
  onTrack(e) {
    debugger
  },
  onTrigger(e) {
    debugger
  }
})

相關用法


注:本文由純淨天空篩選整理自vuejs.org大神的英文原創作品 watchEffect()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。