【Vue】watch中的deep:true源码实现
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了【Vue】watch中的deep:true源码实现,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1911字,纯文字阅读大概需要3分钟。
内容图文
当用户指定了watch中的deep属性为true时,如果当时监控的属性是数组类型,会对对象中的每一项进行求值,此时会将当前watcher存入到对应属性的依赖中,这样数组中对象发生变化时也会通知数据更新。内部原理就是递归,耗费性能 。
整体流程:
initWatch 初期化user watcher(1),user watcher在defineReactive的get中订阅属性的变化(2),在defineReactive的set时触发notify(2),notify调用每个订阅了改属性变化的watcher的update(3),监听 watcher 进入update的queueWatcher,在queueWatcher的nextTick中调用flushSchedulerQueue(4),flushSchedulerQueue中调用监听watcher的run(5),在watcher.run中调用this.get,在this.get中判断this.deep是否为true,为true则执行traverse,在traverse中会因为对属性的取值触发2的get方法,并且traverse递归调用,使当前watch监听到对象内部的每一个属性(6),进而调用用户在watch属性上定义的方法。
1、initWatch 初期化user watcher(src\core\instance\state.js)
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])//每一项创建一个watcher } } else { createWatcher(vm, key, handler) } } }
2、user watcher在defineReactive的get中订阅属性的变化,在defineReactive的set时触发notify
export function defineReactive ( obj: Object, key: string, val: any, customSetter?: ?Function, shallow?: boolean ) { ... Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: function reactiveGetter () { const value = getter ? getter.call(obj) : val if (Dep.target) { dep.depend() if (childOb) { childOb.dep.depend() if (Array.isArray(value)) { dependArray(value) } } } return value }, set: function reactiveSetter (newVal) { ... dep.notify() } }) }
3、notify调用每个订阅了改属性变化的watcher的update
notify () { ... for (let i = 0, l = subs.length; i < l; i++) { subs[i].update() } }
4、queueWatcher(src\core\observer\scheduler.js):
export function queueWatcher (watcher: Watcher) { ... nextTick(flushSchedulerQueue) }
5、调用监听watcher的run
function flushSchedulerQueue () { ... for (index = 0; index < queue.length; index++) { ... watcher.run() ... } ... }
6、traverse
原文:https://www.cnblogs.com/vickylinj/p/14034909.html
内容总结
以上是互联网集市为您收集整理的【Vue】watch中的deep:true源码实现全部内容,希望文章能够帮你解决【Vue】watch中的deep:true源码实现所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。