声明要在数据更改时调用的监视回调。
类型
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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。