2022-03-11 Vue Vue2响应式与依赖收集原理 响应式Vue2的响应式依赖ES5的Object.defineProperty,主要使用这个API改写对象的Getter与Setter,用来依赖收集与触发更新 依赖收集原理123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869// 工具函数用来判断obj是不是一个objectfunction isObject (obj) { return typeof obj === 'object' && !Array.isArray(obj) && obj !== null && obj !== undefined}// `observe`函数用来把一个普通的对象转为响应式对象function observe (obj) { if (!isObject(obj)) { throw new TypeError() } Object.keys(obj).forEach(key => { let internalValue = obj[key] // 每一个属性都有一个独立的依赖收集器 let dep = new Dep() Object.defineProperty(obj, key, { get () { // 这里用来收集依赖 dep.depend() return internalValue }, set (newValue) { const isChanged = internalValue !== newValue if (isChanged) { internalValue = newValue // 如果修改了值,这里用来通知修改 dep.notify() } } }) })}window.Dep = class Dep { constructor () { this.subscribers = new Set() } depend () { if (activeUpdate) { // register the current active update as a subscriber this.subscribers.add(activeUpdate) } } notify () { // run all subscriber functions this.subscribers.forEach(subscriber => subscriber()) }}// activeUpdate是一个运行函数let activeUpdate// 这只是依赖收集的简单示例,示例代码还是存在不少问题的function autorun (update) { // 函数wrappedUpdate这里使用闭包,保存了update方法 function wrappedUpdate () { activeUpdate = wrappedUpdate update() activeUpdate = null } wrappedUpdate()} 前一篇 从开源项目看Maven配置(01) -- dbapi 后一篇 Maven生命周期与插件