用於創建觀察者的命令式 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 函數。
第二個參數是回調函數。回調接收監視源的新值和舊值。
示例
觀察一個屬性名稱:
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()
相關用法
- Vue.js $emit()用法及代碼示例
- Vue.js useSSRContext()用法及代碼示例
- Vue.js app.directive()用法及代碼示例
- Vue.js mergeProps()用法及代碼示例
- Vue.js app.config.warnHandler用法及代碼示例
- Vue.js pipeToWebWritable()用法及代碼示例
- Vue.js app.use()用法及代碼示例
- Vue.js v-pre用法及代碼示例
- Vue.js h()用法及代碼示例
- Vue.js serverPrefetch用法及代碼示例
- Vue.js customRef()用法及代碼示例
- Vue.js <Transition>用法及代碼示例
- Vue.js inject()用法及代碼示例
- Vue.js mixins用法及代碼示例
- Vue.js ComponentCustomProps用法及代碼示例
- Vue.js reactive()用法及代碼示例
- Vue.js ComponentCustomProperties用法及代碼示例
- Vue.js app.mount()用法及代碼示例
- Vue.js <component>用法及代碼示例
- Vue.js createRenderer()用法及代碼示例
- Vue.js onMounted()用法及代碼示例
- Vue.js createApp()用法及代碼示例
- Vue.js app.config.errorHandler用法及代碼示例
- Vue.js v-on用法及代碼示例
- Vue.js components用法及代碼示例
注:本文由純淨天空篩選整理自vuejs.org大神的英文原創作品 $watch()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。