vue 响应式,双向绑定源码解析

1、initState(vm)——初始化porps, methods, data, computed, watch

  1. 地址:src/core/instance/init.js
    初始化porps,methods,data,computed,watch,并注入到vue实例上,并做响应式处理
    2、initData或者observe方法——响应式入口
  2. 地址:src/core/instance/state.js
    进入initState方法,对data进入处理——响应式入口
    export function initState (vm: Component) {
    ......
    if (opts.data) {
    // data做响应式处理
    initData(vm)
    } else {
    observe(vm._data = {}, true /* asRootData */)
    }
    ......
    }

3、observe(value)方法——创建Observer()对象

  1. 地址:src/core/observer/index.js
    判断value是否是对象,不是直接返回
    判断value是否有ob属性,如果有返回;这样做的好处是,如果之前做过响应式处理就可以直接缓存;没有的话创建Observer对象
    返回Observer对象
    export function observe (value: any, asRootData: ?boolean): Observer | void {
    // 判断value是否是对象
    if (!isObject(value) || value instanceof VNode) {
    return
    }
    let ob: Observer | void
    // 如果value有ob(observer对象)属性结束
    // 这样做的好处是,如果之前做过响应式处理就可以直接缓存
    if (hasOwn(value, 'ob') && value.ob instanceof Observer) {
    ob = value.ob
    } else if (
    shouldObserve &&
    !isServerRendering() &&
    (Array.isArray(value) || isPlainObject(value)) &&
    Object.isExtensible(value) &&
    !value._isVue
    ) {
    // 创建一个Observer对象
    ob = new Observer(value)
    }
    if (asRootData && ob) {
    ob.vmCount++
    }
    return ob
    }

4、Observer类——对象,数组处理入口

  1. 地址:src/core/observer/index.js
    每个Observer类都有一个dep对象
    给vaule对象定义ob属性,记录当前的observer对象
    对象的响应式处理,调用walk(value)方法中的defineReactive(obj, keys[i])
    数组的响应式处理,protoAugment(value, arrayMethods)/copyAugment(value, arrayMethods, arrayKeys)
    export class Observer {
    value: any;
    dep: Dep;
    vmCount: number; // number of vms that have this object as root $data

constructor (value: any) {
this.value = value
// 每个Observer类都有一个dep对象
this.dep = new Dep()
this.vmCount = 0
// 将实例挂载到观察对象的ob属性
def(value, 'ob', this)
// 数组响应式处理
if (Array.isArray(value)) {
// 判断当前浏览器对象是否支持proto
// protoAugment,copyAugment,重新修补会改变数组元素的方法
if (hasProto) {
protoAugment(value, arrayMethods)
} else {
copyAugment(value, arrayMethods, arrayKeys)
}
this.observeArray(value)
} else {
// 遍历对象中的每一个属性,转换成setter/getter
this.walk(value)
}
}

/**

  • Walk through all properties 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])
    }
    }
    }

5、defineReactive()方法——对象响应式处理

  1. 地址: src/core/observer/index.js
    为每个属性创建dep对象,这的dep是为了收集依赖与每个Observer类中的dep不一样
    如果当前的值是对象,调用observe
    defineProperty getter
    收集依赖dep.depend(),如果有子对象,同样给子对象收集依赖
    返回属性的值 return value
    defineProperty setter
    保存新值
    如果新值是对象,深度监听,并返回子的observe(newVal)
    派发更新(发送更新通知)dep.notify()
    export function defineReactive (
    obj: Object,
    key: string,
    val: any,
    // 用户自定义函数,很少用到
    customSetter?: ?Function,
    // 是否深度监听
    shallow?: boolean
    ) {
    // 依赖对象实例
    const dep = new Dep()
    // 获取obj的属性描述对象,为obj定义getter,setter,configurable
    const property = Object.getOwnPropertyDescriptor(obj, key)
    // 属性不可配置,也就是不能重新用defineProperty来定义,直接返回
    if (property && property.configurable === false) {
    return
    }

// cater for pre-defined getter/setters
// 有可能用户有些get,set,这样就先取出来,然后重新加入派发和更新
const getter = property && property.get
const setter = property && property.set
// defineReactive只传入两个值的时候,获取到val值
if ((!getter || setter) && arguments.length === 2) {
val = obj[key]
}

// 判断是否是深度监听,并将子对象属性转化为getter/setter,返回子观察对象
let childOb = !shallow && observe(val)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
// 先获取用户传入的getter,如果有则使用用户定义的getter,没有的话就刚才设置的val值
const value = getter ? getter.call(obj) : val
// 收集依赖
// 将依赖改属性的watcher对象添加到dep,将来数据发生变化时通知
// target中存储的是watcher对象
if (Dep.target) {
// depend()方法是进行依赖收集,将watcher对象添加到subs数组中
dep.depend()
if (childOb) {
// 给子对象添加依赖
childOb.dep.depend()
if (Array.isArray(value)) {
dependArray(value)
}
}
}
return value
},
set: function reactiveSetter (newVal) {
// 先获取用户传入的getter,如果有则使用用户定义的getter,没有的话就刚才设置的val值
const value = getter ? getter.call(obj) : val
/* eslint-disable no-self-compare /
// 判断新值与旧值是否相同,如果新值或旧值为NaN则不执行
if (newVal === value || (newVal !== newVal && value !== value)) {
return
}
/
eslint-enable no-self-compare */
if (process.env.NODE_ENV !== 'production' && customSetter) {
customSetter()
}
// #7981: for accessor properties without setter
// 如果getter存在,setter不存在,只读,直接返回
if (getter && !setter) return
// setter存在,则调用,否则直接更新数值
if (setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
// 新值是对象,深度监听,并返回子的observer对象
childOb = !shallow && observe(newVal)
// 派发更新(发布更新通知)
dep.notify()
}
})
}

6、if(Dep.target){dep.depend()...}——收集依赖

  1. 将watcher对象记录到Dep.target中
  2. 地址:src/core/observer/index.js
    Dep.target,target中存储的是watcher对象,找到watcher定义的地方,查看什么时候给Dep.target赋值
  3. 地址: src/core/instance/lifecycle.js
    new Watcher(vm,undateComponent,...)进入watcher对象
  4. 地址: src/core/observer/watcher.js
    Watcher类中,定义了很多属性,将定义的watcher对象this,存储到vue实例的watchers数组中
    // 渲染watcher,侦听器watcher,计算属性watcher都会记录到_watcher中
    // 将定义的watcher对象this,存储到vue实例的watchers数组中
    vm._watchers.push(this)

调用get方法中的pushTarget(this),this也就是当前的watcher,记录当前watcher,进入pushTarget
watcher的get方法,每次访问属性时都会执行,首次渲染会执行,数据改变也会执行,也就是当我们访问时会收集依赖
访问data中的成员的时候收集依赖,触发defineReactive的getter时收集依赖
// this也就是将当前的watcher对象记录下来
get () {
pushTarget(this)
......
}

  1. 地址:src/core/observer/dep.js
    入栈并将当前的watcher赋值记录Dep.target中
    // 当前target用来存放目前正在使用的watcher
    // 全局唯一,并且一次也只能又一个watcher被使用
    Dep.target = null
    const targetStack = []
    // 入栈并将当前watcher赋值给Dep.target
    // vue2后每个组件对应一个watcher对象,组件有嵌套,B是A的子组件,渲染A时,先渲染B组件,
    // A渲染过程被挂载起来,A的watcher先存储到栈中,B渲染完,把父组件watcher出栈,然后父组件渲染
    export function pushTarget (target: ?Watcher) {
    targetStack.push(target)
    Dep.target = target
    }

  2. dep.depend()——将watcher对象添加到dep对象的subs数组中

  3. 回到地址:src/core/observer/index.js
    进入depend()方法

  4. 地址: src/core/observer/dep.js
    depend()方法将dep对象添加到watcher的依赖中,addDep(this)

  5. 地址:src/core/observer/watcher.js
    主要是将watcher对象添加到了subs数组中,dep.addSub(this),添加到subs数组中
    // 主要是watcher对象添加到了subs数组中
    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)
    }
    }
    }

addSub (sub: Watcher) {
this.subs.push(sub)
}

  1. 存在子对象的话,给子对象也添加依赖,目的是子对象添加和删除成员时发送通知
    if (childOb) {
    // 给子对象添加依赖
    childOb.dep.depend()
    if (Array.isArray(value)) {
    dependArray(value)
    }
    }

7、protoAugment(value, arrayMethods)——数组的响应式处理

  1. 地址: src/core/observer/index.js
    protoAugment(value, arrayMethods),copyAugment,arrayMethods重新修补会改变数组元素的方法
  2. 地址:src/core/observer/array.js
    对数组,push,pop,shigt,unshift,splice,sort,reverse,这些方法会改变原数组,进行修补变成响应式,先找到数组对象的ob,然后再找到dep,调用notify()发送通知
    const arrayProto = Array.prototype
    // 使用数组原型创建一个新的对象
    export const arrayMethods = Object.create(arrayProto)
    // 修改数组元素的方法
    const methodsToPatch = [
    'push',
    'pop',
    'shift',
    'unshift',
    'splice',
    'sort',
    'reverse'
    ]

/**

  • Intercept mutating methods and emit events
    */
    // 将数组方法循环
    methodsToPatch.forEach(function (method) {
    // cache original method
    // 将原数组的方法赋值给original
    const original = arrayProto[method]
    // 调用object,defineProperty()重新定义修改数组的方法
    def(arrayMethods, method, function mutator (...args) {
    // 执行数组的原始方法
    const result = original.apply(this, args)
    // 获取数组对象的ob对象
    const ob = this.ob
    // 存储数组中新增的元素
    let inserted
    switch (method) {
    case 'push':
    case 'unshift':
    inserted = args
    break
    case 'splice':
    inserted = args.slice(2)
    break
    }
    // 对插入的新元素,重新遍历数组元素设置为响应式数据
    if (inserted) ob.observeArray(inserted)
    // notify change
    // 调用了修改数组的方法,调用数组的ob对象发送通知
    ob.dep.notify()
    return result
    })
    })

8、watcher——dep.notify()调用watcher中的update()方法发布更新通知

  1. 地址: src/core/observer/index.js 与 src/core/observer/dep.js
    dep.notify() 派发更新,调用watcher中的update()方法
    notify () {
    // stabilize the subscriber list first
    const subs = this.subs.slice()
    if (process.env.NODE_ENV !== 'production' && !config.async) {
    // subs aren't sorted in scheduler if not running async
    // we need to sort them now to make sure they fire in correct
    // order
    // 排序,按照watcher的创建顺序
    subs.sort((a, b) => a.id - b.id)
    }
    for (let i = 0, l = subs.length; i < l; i++) {
    // 更新
    subs[i].update()
    }
    }

  2. 地址:src/core/observer/dep.js
    update()方法中执行渲染watcher,queueWatcher(this)
    update () {
    /* istanbul ignore else */
    if (this.lazy) {
    this.dirty = true
    } else if (this.sync) {
    this.run()
    } else {
    // 渲染watcher执行
    queueWatcher(this)
    }
    }

  3. 地址: src/core/observer/scheduler.js
    queueWatcher(),判断watcher现在是否正在处理,如果没有放入queue队列末尾,并触发flushSchedulerQueue()
    export function queueWatcher (watcher: Watcher) {
    ......
    // flushing正在处理,如果没有正在处理,就将watcher放到队列的末尾
    if (!flushing) {
    queue.push(watcher)
    } else {
    ......
    }
    // queue the flush
    if (!waiting) {
    waiting = true
    ......
    // 触发flushSchedulerQueue
    nextTick(flushSchedulerQueue)
    }
    }
    }

  4. 地址:src/core/observer/scheduler.js
    触发beforeUpdate()钩子函数
    调用run方法,run()->get()->触发getter(渲染watcher实际调用updateComponent位置)->updateComponent
    updateComponent会执行vm._update(vm._render())
    watcher.run()方法执行后可以在页面中看到真正的数据,这时候已经处理完成,剩下一些清理工作
    // 调用run方法,watcher.run()后就可以在页面中看到真正的数据
    watcher.run()

const value = this.get()

// 渲染watcher实际调用updateComponent位置
value = this.getter.call(vm, vm)

清空上一次的依赖
触发activated钩子函数
触发updated钩子函数
// 触发beforeUpadate
if (watcher.before) {
watcher.before()
}
......
// 调用run方法,watcher.run()后就可以在页面中看到真正的数据
watcher.run()
......
// 清空上一次的依赖
resetSchedulerState()

// 触发activated钩子函数
callActivatedHooks(activatedQueue)
// 触发updated钩子函数
callUpdatedHooks(updatedQueue)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容