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


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

用於創建觀察者的命令式 API。

類型

interface ComponentPublicInstance {
  $watch(
    source: string | (() => any),
    callback: WatchCallback,
    options?: WatchOptions
  ): StopHandle
}

type WatchCallback<T> = (
  value: T,
  oldValue: T,
  onCleanup: (cleanupFn: () => void) => void
) => void

interface WatchOptions {
  immediate?: boolean // default: false
  deep?: boolean // default: false
  flush?: 'pre' | 'post' | 'sync' // default: 'pre'
  onTrack?: (event: DebuggerEvent) => void
  onTrigger?: (event: DebuggerEvent) => void
}

type StopHandle = () => void

細節

第一個參數是監視源。它可以是組件屬性名稱字符串、簡單的dot-delimited 路徑字符串或getter 函數。

第二個參數是回調函數。回調接收監視源的新值和舊值。

  • immediate:在觀察者創建時立即觸發回調。舊值將是undefined在第一次調用。
  • deep:如果源是對象,則強製深度遍曆源,以便回調觸發深度突變。看深度觀察者.
  • flush:調整回調的刷新時間。看回調刷新時間.
  • onTrack / onTrigger: 調試觀察者的依賴。看觀察者調試.

示例

觀察一個屬性名稱:

this.$watch('a', (newVal, oldVal) => {})

觀看 dot-delimited 路徑:

this.$watch('a.b', (newVal, oldVal) => {})

對更複雜的表達式使用 getter:

this.$watch(
  // every time the expression `this.a + this.b` yields
  // a different result, the handler will be called.
  // It's as if we were watching a computed property
  // without defining the computed property itself.
  () => this.a + this.b,
  (newVal, oldVal) => {}
)

停止觀察者:

const unwatch = this.$watch('a', cb)

// later...
unwatch()

相關用法


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