企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持知识库和私有化部署方案 广告
## watch 、 vm.$watch ### watch watch和vm.$watch功能是相同的 初始化 watch 是通过循环 watch 选项,将对象每一项调用vm.$watch方法来实现。 ``` function initWatch (vm: Component, watch: Object) { for (const key in watch) { const handler = watch[key] if (Array.isArray(handler)) { for (let i = 0; i < handler.length; i++) { createWatcher(vm, key, handler[i]) } } else { createWatcher(vm, key, handler) } } } function createWatcher ( vm: Component, expOrFn: string | Function, handler: any, options?: Object ) { if (isPlainObject(handler)) { options = handler handler = handler.handler } if (typeof handler === 'string') { handler = vm[handler] } return vm.$watch(expOrFn, handler, options) } ``` ### vm.$watch vm.$watch 是对 Watcher 的一种封装,多了参数 deep 和 immediate #### 使用: * vm.$watch第一个参数可以是字符串,也可以是 **function**,用来观察表达式或者**函数执行结果**的变化。 * 当第一个参数是函数时,函数中使用的数据都会被 Watcher 观察,这个Watcher 就会被存储到多个 Dep中。 * vm.$watch返回取消观察的函数,调用这个可以用来取消回调函数的触发。 ``` vm.$watch ('a.b.c', function ( newVal, oldVal ) { ... }) vm.$watch( function () { return this.a + this.b }, function (newVal, oldVal) { ... } ) ``` #### 实现: ``` Vue.prototype.$watch = function ( expOrFn: string | Function, cb: any, options?: Object ): Function { const vm: Component = this if (isPlainObject(cb)) { return createWatcher(vm, expOrFn, cb, options) } options = options || {} options.user = true const watcher = new Watcher(vm, expOrFn, cb, options) if (options.immediate) { const info = `callback for immediate watcher "${watcher.expression}"` pushTarget() invokeWithErrorHandling(cb, vm, \[watcher.value\], vm, info) popTarget() } return function unwatchFn () { watcher.teardown() } } } ``` ### deep 实现原理 当前值的子值都触发一边依赖收集,这样 Watcher 就可以观察到子值了