聲明要在數據更改時調用的監視回調。
類型
interface ComponentOptions {
watch?: {
[key: string]: WatchOptionItem | WatchOptionItem[]
}
}
type WatchOptionItem = string | WatchCallback | ObjectWatchOptionItem
type WatchCallback<T> = (
value: T,
oldValue: T,
onCleanup: (cleanupFn: () => void) => void
) => void
type ObjectWatchOptionItem = {
handler: WatchCallback | string
immediate?: boolean // default: false
deep?: boolean // default: false
flush?: 'pre' | 'post' | 'sync' // default: 'pre'
onTrack?: (event: DebuggerEvent) => void
onTrigger?: (event: DebuggerEvent) => void
}
為了便於閱讀,類型被簡化了。
細節
watch
選項需要一個對象,其中鍵是要觀察的反應組件實例屬性(例如,通過 data
或 computed
聲明的屬性) - 值是相應的回調。回調接收監視源的新值和舊值。
除了 root-level 屬性之外, key 還可以是簡單的 dot-delimited 路徑,例如a.b.c
.請注意,這種用法確實不是支持複雜的表達式 - 僅支持 dot-delimited 路徑。如果您需要查看複雜的數據源,這勢在必行$watch()取而代之的是 API。
該值也可以是方法名稱的字符串(通過 methods
聲明)或包含附加選項的對象。使用對象語法時,應在handler
字段下聲明回調。其他選項包括:
immediate
:在觀察者創建時立即觸發回調。舊值將是undefined
在第一次調用。deep
:如果源是對象或數組,則強製對源進行深度遍曆,以便回調觸發深度突變。看深度觀察者.flush
:調整回調的刷新時間。看回調刷新時間.onTrack / onTrigger
: 調試觀察者的依賴。看觀察者調試.
在聲明監視回調時避免使用箭頭函數,因為它們無法通過 this
訪問組件實例。
示例
export default {
data() {
return {
a: 1,
b: 2,
c: {
d: 4
},
e: 5,
f: 6
}
},
watch: {
// watching top-level property
a(val, oldVal) {
console.log(`new: ${val}, old: ${oldVal}`)
},
// string method name
b: 'someMethod',
// the callback will be called whenever any of the watched object properties change regardless of their nested depth
c: {
handler(val, oldVal) {
console.log('c changed')
},
deep: true
},
// watching a single nested property:
'c.d': function (val, oldVal) {
// do something
},
// the callback will be called immediately after the start of the observation
e: {
handler(val, oldVal) {
console.log('e changed')
},
immediate: true
},
// you can pass array of callbacks, they will be called one-by-one
f: [
'handle1',
function handle2(val, oldVal) {
console.log('handle2 triggered')
},
{
handler: function handle3(val, oldVal) {
console.log('handle3 triggered')
}
/* ... */
}
]
},
methods: {
someMethod() {
console.log('b changed')
},
handle1() {
console.log('handle 1 triggered')
}
},
created() {
this.a = 3 // => new: 3, old: 1
}
}
相關用法
- Vue.js watch()用法及代碼示例
- Vue.js watchEffect()用法及代碼示例
- 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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。