Vue2 响应式原理小结
为了面试讲Vu2响应式的时候更顺利点,我想在需要提前准备一下:
Vue2.5.17 的源码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | export class Observer { value: any; dep: Dep; vmCount: number; // number of vms that has this object as root $data constructor (value: any) { this .value = value this .dep = new Dep() this .vmCount = 0 def(value, '__ob__' , this ) // 给入参加上 __ob__ 作为一个响应式的标志符号,随便指向Observer(被观测)对象本身 if (Array.isArray(value)) { const augment = hasProto ? protoAugment : copyAugment augment(value, arrayMethods, arrayKeys) this .observeArray(value) } else { this .walk(value) } } /** * Walk through each property and convert them into * getter/setters. This method should only be called when * value type is Object. */ walk (obj: Object) { const keys = Object.keys(obj) for ( let i = 0; i < keys.length; i++) { defineReactive(obj, keys[i]) } } /** * Observe a list of Array items. */ observeArray (items: Array<any>) { for ( let i = 0, l = items.length; i < l; i++) { observe(items[i]) } } } |
先说下Observer吧,Observer的构造函数吧,就是让一个(value 入参)对象拥有响应式能力,赋能的函数叫做 defineReactive,我们细聊一下 defineReactive。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | export function defineReactive ( obj: Object, key: string, val: any, customSetter?: ?Function, shallow?: boolean ) { const dep = new Dep() const property = Object.getOwnPropertyDescriptor(obj, key) if (property && property.configurable === false ) { return } // cater for pre-defined getter/setters const getter = property && property.get const setter = property && property.set if ((!getter || setter) && arguments.length === 2) { val = obj[key] } let childOb = !shallow && observe(val) // 关键在于这里了 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) { const value = getter ? getter.call(obj) : val /* eslint-disable no-self-compare */ if (newVal === value || (newVal !== newVal && value !== value)) { return } /* eslint-enable no-self-compare */ if (process.env.NODE_ENV !== 'production' && customSetter) { customSetter() } if (setter) { setter.call(obj, newVal) } else { val = newVal } childOb = !shallow && observe(newVal) dep.notify() } }) } |
1 | Object.defineProperty(obj, key, {???}) 侵入了一个对象的get set过程。对于get过程,Observe对象内部的成员dep ,它是一种Dep类型的对象,Dep呢,就是depend的缩写了,就是依赖的意思。 |
1 | Dep有一个depend()函数,depend()函数呢,又是一个搜集的动作!这里具体的实现代码,就是向Dep.target 这个数组(池子)里面pushTarget了Dep类型的实例,具体可以看源码,就是 Dep.target.addDep( this )。然后就是Watcher对应addDep()方法,这是一个根据dep的id,来判断是否要进行收集的一个方法,已经收集过的dep不会被搜集。 |
好了,说完了get,我们就来说set。我们可以看到 dep.notify(),相关的代码也是Dep类中定义的,关键就是subs[i].update(),subs数组是Dep类型对象中的成员变量,是subscription类型的集合,引 申为订阅者(subscriber)合集。顾名思义,订阅者要接受消费者观察到的依赖分发。Vue2中定义的sub的类型是Watcher(观察者),在Dep中,subs属于观察者,观察Dep的动作。update()方法就涉及到了 Watcher下面的run()方法以及queueWatcher()一个是立刻执行了,一个是加入了队列,也就交给了我们喜闻乐见的调度器Scheduler。先说一下run()方法吧,也就是getAndInvoke(callback)方法吧,callback()。getAndInvoke执行了所观察(observe)对象的get(),pushTarget 然后 popTarget锁住Dep.target 池,中间过程就是触发了对象的新的值newValue的获取这个动作,连同着oldValue然后再执行了callback的本体回调。
对于渲染 watcher
而言,它在执行 this.get()
方法求值的时候,会执行 getter
方法:会触发组件重新渲染
1 2 3 | updateComponent = () => { vm._update(vm._render(), hydrating) } |
1 2 3 4 5 6 7 | new Watcher(vm, updateComponent, noop, { before () { if (vm._isMounted) { callHook(vm, 'beforeUpdate' ) } } }, true /* isRenderWatcher */ ) |
接下里贴一下 Dep的代码:看看其他的功能
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | export default class Dep { static target: ?Watcher; id: number; subs: Array<Watcher>; constructor () { this .id = uid++ this .subs = [] } // 添加 addSub (sub: Watcher) { this .subs.push(sub) } //移除依赖 removeSub (sub: Watcher) { remove( this .subs, sub) } // 搜集依赖 depend () { if (Dep.target) { Dep.target.addDep( this ) } } notify () { // stabilize the subscriber list first const subs = this .subs.slice() for ( let i = 0, l = subs.length; i < l; i++) { subs[i].update() } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 | export default class Watcher { vm: Component; expression: string; cb: Function; id: number; deep: boolean; user: boolean; computed: boolean; sync: boolean; dirty: boolean; active: boolean; dep: Dep; deps: Array<Dep>; newDeps: Array<Dep>; depIds: SimpleSet; newDepIds: SimpleSet; before: ?Function; getter: Function; value: any; constructor ( vm: Component, expOrFn: string | Function, cb: Function, options?: ?Object, isRenderWatcher?: boolean ) { this .vm = vm if (isRenderWatcher) { vm._watcher = this } vm._watchers.push( this ) // options if (options) { this .deep = !!options.deep this .user = !!options.user this .computed = !!options.computed this .sync = !!options.sync this .before = options.before } else { this .deep = this .user = this .computed = this .sync = false } this .cb = cb this .id = ++uid // uid for batching this .active = true this .dirty = this .computed // for computed watchers this .deps = [] this .newDeps = [] this .depIds = new Set() this .newDepIds = new Set() this .expression = process.env.NODE_ENV !== 'production' ? expOrFn.toString() : '' // parse expression for getter if ( typeof expOrFn === 'function' ) { this .getter = expOrFn } else { this .getter = parsePath(expOrFn) if (! this .getter) { this .getter = function () {} process.env.NODE_ENV !== 'production' && warn( `Failed watching path: "${expOrFn}" ` + 'Watcher only accepts simple dot-delimited paths. ' + 'For full control, use a function instead.' , vm ) } } if ( this .computed) { this .value = undefined this .dep = new Dep() } else { this .value = this .get() } } /** * Evaluate the getter, and re-collect dependencies. */ get () { pushTarget( this ) let value const vm = this .vm try { value = this .getter.call(vm, vm) } catch (e) { if ( this .user) { handleError(e, vm, `getter for watcher "${this.expression}" `) } else { throw e } } finally { // "touch" every property so they are all tracked as // dependencies for deep watching if ( this .deep) { traverse(value) } popTarget() this .cleanupDeps() } return value } /** * Add a dependency to this directive. */ addDep (dep: Dep) { const id = dep.id if (! this .newDepIds.has(id)) { this .newDepIds.add(id) this .newDeps.push(dep) if (! this .depIds.has(id)) { dep.addSub( this ) } } } /** * Clean up for dependency collection. */ cleanupDeps () { let i = this .deps.length while (i--) { const dep = this .deps[i] if (! this .newDepIds.has(dep.id)) { dep.removeSub( this ) } } let tmp = this .depIds this .depIds = this .newDepIds this .newDepIds = tmp this .newDepIds.clear() tmp = this .deps this .deps = this .newDeps this .newDeps = tmp this .newDeps.length = 0 } /** * Subscriber interface. * Will be called when a dependency changes. */ update () { /* istanbul ignore else */ if ( this .computed) { // A computed property watcher has two modes: lazy and activated. // It initializes as lazy by default, and only becomes activated when // it is depended on by at least one subscriber, which is typically // another computed property or a component's render function. if ( this .dep.subs.length === 0) { // In lazy mode, we don't want to perform computations until necessary, // so we simply mark the watcher as dirty. The actual computation is // performed just-in-time in this.evaluate() when the computed property // is accessed. this .dirty = true } else { // In activated mode, we want to proactively perform the computation // but only notify our subscribers when the value has indeed changed. this .getAndInvoke(() => { this .dep.notify() }) } } else if ( this .sync) { this .run() } else { queueWatcher( this ) } } /** * Scheduler job interface. * Will be called by the scheduler. */ run () { if ( this .active) { this .getAndInvoke( this .cb) } } getAndInvoke (cb: Function) { const value = this .get() if ( value !== this .value || // Deep watchers and watchers on Object/Arrays should fire even // when the value is the same, because the value may // have mutated. isObject(value) || this .deep ) { // set new value const oldValue = this .value this .value = value this .dirty = false if ( this .user) { try { cb.call( this .vm, value, oldValue) } catch (e) { handleError(e, this .vm, `callback for watcher "${this.expression}" `) } } else { cb.call( this .vm, value, oldValue) } } } /** * Evaluate and return the value of the watcher. * This only gets called for computed property watchers. */ evaluate () { if ( this .dirty) { this .value = this .get() this .dirty = false } return this .value } /** * Depend on this watcher. Only for computed property watchers. */ depend () { if ( this .dep && Dep.target) { this .dep.depend() } } /** * Remove self from all dependencies' subscriber list. */ teardown () { if ( this .active) { // remove self from vm's watcher list // this is a somewhat expensive operation so we skip it // if the vm is being destroyed. if (! this .vm._isBeingDestroyed) { remove( this .vm._watchers, this ) } let i = this .deps.length while (i--) { this .deps[i].removeSub( this ) } this .active = false } } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端