監視一個或多個響應式數據源並在源更改時調用回調函數。
類型
// watching single source
function watch<T>(
source: WatchSource<T>,
callback: WatchCallback<T>,
options?: WatchOptions
): StopHandle
// watching multiple sources
function watch<T>(
sources: WatchSource<T>[],
callback: WatchCallback<T[]>,
options?: WatchOptions
): StopHandle
type WatchCallback<T> = (
value: T,
oldValue: T,
onCleanup: (cleanupFn: () => void) => void
) => void
type WatchSource<T> =
| Ref<T> // ref
| (() => T) // getter
| T extends object
? T
: never // reactive object
interface WatchOptions extends WatchEffectOptions {
immediate?: boolean // default: false
deep?: boolean // default: false
flush?: 'pre' | 'post' | 'sync' // default: 'pre'
onTrack?: (event: DebuggerEvent) => void
onTrigger?: (event: DebuggerEvent) => void
}
為了便於閱讀,類型被簡化了。
細節
watch()
默認情況下是惰性的 - 即僅當監視的源發生更改時才調用回調。
第一個參數是觀察者的來源。源可以是以下之一:
- 返回值的getter函數
- 一個參考
- 反應性對象
- ...或上述數組。
第二個參數是源更改時將調用的回調。回調接收三個參數:新值、舊值和用於注冊副作用清除回調的函數。清理回調將在下一次重新運行效果之前調用,可用於清理無效的副作用,例如待處理的異步請求。
當觀察多個源時,回調接收到兩個數組,其中包含與源數組對應的新/舊值。
第三個可選參數是一個支持以下選項的選項對象:
immediate
:在觀察者創建時立即觸發回調。舊值將是undefined
在第一次調用。deep
:如果源是對象,則強製深度遍曆源,以便回調觸發深度突變。看深度觀察者.flush
:調整回調的刷新時間。看回調刷新時間.onTrack / onTrigger
: 調試觀察者的依賴。看觀察者調試.
與
相比,watchEffect()
watch()
允許我們:
- 懶惰地執行副作用;
- 更具體地說明應該觸發觀察者重新運行的狀態;
- 訪問監視狀態的先前值和當前值。
示例
觀察吸氣劑:
const state = reactive({ count: 0 })
watch(
() => state.count,
(count, prevCount) => {
/* ... */
}
)
觀看裁判:
const count = ref(0)
watch(count, (count, prevCount) => {
/* ... */
})
當觀察多個源時,回調接收包含與源數組對應的新/舊值的數組:
watch([fooRef, barRef], ([foo, bar], [prevFoo, prevBar]) => {
/* ... */
})
使用 getter 源時,僅當 getter 的返回值發生更改時才會觸發觀察程序。如果您希望即使在深度突變時也能觸發回調,則需要使用 { deep: true }
顯式強製觀察者進入深度模式。請注意,在深度模式下,如果回調是由深度突變觸發的,則新值和舊值將是同一個對象:
const state = reactive({ count: 0 })
watch(
() => state,
(newValue, oldValue) => {
// newValue === oldValue
},
{ deep: true }
)
當直接觀察反應對象時,觀察者自動處於深度模式:
const state = reactive({ count: 0 })
watch(state, () => {
/* triggers on deep mutation to state */
})
watch()
與
共享相同的刷新時間和調試選項:watchEffect()
watch(source, callback, {
flush: 'post',
onTrack(e) {
debugger
}
})
相關用法
- Vue.js watchEffect()用法及代碼示例
- Vue.js watch用法及代碼示例
- Vue.js withDirectives()用法及代碼示例
- Vue.js withModifiers()用法及代碼示例
- 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()用法及代碼示例
注:本文由純淨天空篩選整理自vuejs.org大神的英文原創作品 watch()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。