解析vue2.x源码之Object与Array的变化侦测

9 篇文章 0 订阅
8 篇文章 0 订阅

基本概念介绍:

Vue框架是如何实现变量的变化侦测的呢?

Object 利用了 Object.defineProperty 进行变量的getter与setter拦截,但数组的实现与 Object 有所不同,下面会从源码层面具体讨论这两种类型的变量如何实现变化侦测。

首先我们需要先了解Vue源码中的三个类:

一、Observer

Observer类负责将复杂类型的变量转化成响应式数据,转化为响应式数据的变量都会带有 '__ob__'  属性,所以 '__ob__' 属性可以作为判断响应式数据的标识。

举个例子:

...
  data() {
    return {
      list: [1, 2, 3],
      obj:{
        a: 1,
        b: 2,
        c: 3
      },
      num: 1
    };
  },
  created() {
    console.log(this);
  }
...

输出台得到的结果:

因为list 和 obj 是复杂类型,被Observer处理成了响应式数据,带有'__ob__' 属性,而num是简单数据类型,所以没有被Observer处理。

 

二、Watcher

当我们侦测到数据发生变化时,需要通知给谁呢? 

需要用到这个数据的地方有很多,可能是我们自定义的,也有可能是模板上的,我们把这些地方统称为watcher,可以理解成依赖。

 

三、Dep

dep的作用在于收集依赖,当侦测到数据发生变化时,dep会通知他收集的所有watch。

dep 与 watch是多对多的关系,一个dep可以收集多个watch,一个watch可以订阅多个依赖。

 

知道了这三个类,我们就能理解这张流程图(图片出自《深入浅出Vue.js》):

数据data进过observer处理变成影响式数据,数据的getter与setter被拦截。

每当有watcher到data读取数据时,会被getter拦截,watcher被当做依赖被dep收集。

每当Data的数据发生变化时会被setter拦截,setter会通知Dep,Dep再通知它收集的所有watcher, watcher再调用它的回调函数。

但我们前面讲过数组的变化侦测实现原理有所不同,当我们通过key读取数组时,一样会被getter拦截。

但是由于Object.defineProperty的setter只能做到对每个key进行拦截,当数组调用原生方法如push或pop时,数组值发生变化,

Object.defineProperty却拦截不到,所以数组值的变化侦测只能通过重写数组的原生方法实现拦截。

接下来我们进一步分析源码:

重写Array原生方法

// 拷贝数组的原型到原型链上
const arrayProto = Array.prototype
export const arrayMethods = Object.create(arrayProto)

// 需要重写的方法名
const methodsToPatch = [
  'push',
  'pop',
  'shift',
  'unshift',
  'splice',
  'sort',
  'reverse'
]

def (obj: Object, key: string, val: any, enumerable?: boolean) {
  Object.defineProperty(obj, key, {
    value: val,
    enumerable: !!enumerable,
    writable: true,
    configurable: true
  })
}

methodsToPatch.forEach(function (method) {
  // 保存数组原有方法
  const original = arrayProto[method]
  // 重写方法
  def(arrayMethods, method, function mutator (...args) {
    // 调用数组原有方法
    const result = original.apply(this, args)
    // 取出__ob__属性上的observer实例
    const ob = this.__ob__
    let inserted
    switch (method) {
      case 'push':
      case 'unshift':
        inserted = args
        break
      case 'splice':
        inserted = args.slice(2)
        break
    }
    // inserted 代表新增的数据,将这部分数据也处理成响应式数据
    if (inserted) ob.observeArray(inserted)
    // 通知dep收集的所有watcher,数组值发生了改变
    ob.dep.notify()
    return result
  })
})

Dep类

let uid = 0
export default class Dep {
  static target: ?Watcher; //当前正在处理的watcher
  id: number; // 唯一标识
  subs: Array<Watcher>; // 收集的watcher

  constructor () {
    this.id = uid++
    this.subs = []
  }
  // 收集watcher
  addSub (sub: Watcher) {
    this.subs.push(sub)
  }
  // 移除watcher
  removeSub (sub: Watcher) {
    remove(this.subs, sub)
  }
  // 使watcher订阅当前dep
  depend () {
    if (Dep.target) {
      Dep.target.addDep(this)
    }
  }
  // 通知收集的所有watcher
  notify () {
    const subs = this.subs.slice()
    if (process.env.NODE_ENV !== 'production' && !config.async) {
      subs.sort((a, b) => a.id - b.id)
    }
    for (let i = 0, l = subs.length; i < l; i++) {
      subs[i].update()
    }
  }
}
// 初始化数据
Dep.target = null
const targetStack = []

// 重点!当外部调用pushTarget传入一个watcher时
// 该watcher置于栈顶,Dep.target赋值为该watcher
// 此时如果调用Dep实例的depend方法,该Dep实例会被watcher订阅
export function pushTarget (target: ?Watcher) {
  targetStack.push(target)
  Dep.target = target
}
// 弹出最顶层的watcher,Dep.target赋值为下一个watcher
export function popTarget () {
  targetStack.pop()
  Dep.target = targetStack[targetStack.length - 1]
}

watcher类

let uid = 0
export default class Watcher {
  vm: Component; // 组件实例
  expression: string;
  cb: Function; // 回调函数
  id: number; // 唯一标识
  deep: boolean; // 是否深度监听
  user: boolean; // 是否用户自定义的watcher
  lazy: boolean; // 是否马上监听变量
  sync: boolean; // 是否马上执行
  dirty: boolean;
  active: boolean;
  deps: Array<Dep>; // 目前订阅当前watcher的dep数组
  newDeps: Array<Dep>; // 新订阅当前watcher的dep数组
  depIds: SimpleSet; // 目前订阅当前watcher的dep的id数组
  newDepIds: SimpleSet; // 新订阅当前watcher的dep的id数组
  before: ?Function;
  getter: Function; // 调用可获取监听对象的最新值
  value: any; // 监听对象的值

  constructor (
    vm: Component,
    expOrFn: string | Function, // 监听对象,可能是字符串 a.b.c的形式或者一个函数
    cb: Function,
    options?: ?Object, // 配置参数
    isRenderWatcher?: boolean
  ) {
    this.vm = vm
    if (isRenderWatcher) {
      vm._watcher = this
    }
    vm._watchers.push(this)
    // 初始化参数
    if (options) {
      this.deep = !!options.deep
      this.user = !!options.user
      this.lazy = !!options.lazy
      this.sync = !!options.sync
      this.before = options.before
    } else {
      this.deep = this.user = this.lazy = this.sync = false
    }
    this.cb = cb
    this.id = ++uid // id递增
    this.active = true
    this.dirty = this.lazy // for lazy watchers
    this.deps = []
    this.newDeps = []
    this.depIds = new Set()
    this.newDepIds = new Set()
    this.expression = process.env.NODE_ENV !== 'production'
      ? expOrFn.toString()
      : ''
    if (typeof expOrFn === 'function') {
      this.getter = expOrFn
    } else {
      // parsePath函数用于解析a.b.c字符串,返回值为a[b][c]
      this.getter = parsePath(expOrFn)
      if (!this.getter) {
        this.getter = noop // noop 是一个返回空值的函数
        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
        )
      }
    }
    // 只要不是lazy watcher,在watcher构造函数中就会调用get方法
    this.value = this.lazy
      ? undefined
      : this.get()
  }

  get () {
    // 调用pushTarget方法,使Dep.target赋值为当前watcher,开始订阅dep
    pushTarget(this)
    let value
    const vm = this.vm
    try {
      // 调用getter读取当前监听对象的值,此时会被getter拦截
      // watcher作为依赖被收集,同时订阅监听对象的dep
      value = this.getter.call(vm, vm)
    } catch (e) {
      if (this.user) {
        handleError(e, vm, `getter for watcher "${this.expression}"`)
      } else {
        throw e
      }
    } finally {
      // 如果是深度监听,则遍历读取每个子属性,原理同上
      if (this.deep) {
        traverse(value)
      }
      popTarget() // 取消监听
      this.cleanupDeps()
    }
    return value
  }

  // 订阅dep
  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)
      }
    }
  }

  // 将deps清空,newDeps赋值给deps
  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
  }

  // 收到通知,调用run()
  update () {
    /* istanbul ignore else */
    if (this.lazy) {
      this.dirty = true
    } else if (this.sync) { // 同步马上调用
      this.run()
    } else { // queueWatcher会在下一次事件循环中调用 run()
      queueWatcher(this)
    }
  }

  // 调用回调函数
  run () {
    if (this.active) {
      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
        if (this.user) {
          try {
            this.cb.call(this.vm, value, oldValue)
          } catch (e) {
            handleError(e, this.vm, `callback for watcher "${this.expression}"`)
          }
        } else {
          this.cb.call(this.vm, value, oldValue)
        }
      }
    }
  }
  ...
}

Observer类

// arrayMethods是重写了数组方法的对象
const arrayKeys = Object.getOwnPropertyNames(arrayMethods)

// 监听开关
export let shouldObserve: boolean = true

export class Observer {
  value: any; // 需要被转化成响应式数据的对象
  dep: Dep; // 重点!用于收集数组的依赖,只有数组会通过这个Dep通过watcher。
  vmCount: number; // number of vms that have this object as root $data

  constructor (value: any) {
    this.value = value
    this.dep = new Dep()
    this.vmCount = 0
    // 当前Observer实例被挂到数据的'__ob__',也标识了这个数据成为响应式数据
    def(value, '__ob__', this)
    if (Array.isArray(value)) {
      if (hasProto) { // 如果浏览器支持__proto__,直接将arrayMethods挂到value.__proto__上
        protoAugment(value, arrayMethods)
      } else { // 不支持__proto__,则将arrayMethods的方法直接加到value上
        copyAugment(value, arrayMethods, arrayKeys)
      }
      // 进一步将数组中元素也变成响应式数据
      this.observeArray(value)
    } else {
      // 非数组,则是Object
      this.walk(value)
    }
  }

  walk (obj: Object) {
    const keys = Object.keys(obj)
    for (let i = 0; i < keys.length; i++) {
      defineReactive(obj, keys[i])
    }
  }

  observeArray (items: Array<any>) {
    for (let i = 0, l = items.length; i < l; i++) {
      observe(items[i])
    }
  }
}


function protoAugment (target, src: Object) {
  /* eslint-disable no-proto */
  target.__proto__ = src
  /* eslint-enable no-proto */
}

function copyAugment (target: Object, src: Object, keys: Array<string>) {
  for (let i = 0, l = keys.length; i < l; i++) {
    const key = keys[i]
    def(target, key, src[key])
  }
}

// 如果value有__ob__,说明已经是响应式数据,无需处理,否则需要通过Observer类进行处理
export function observe (value: any, asRootData: ?boolean): Observer | void {
  if (!isObject(value) || value instanceof VNode) {
    return
  }
  let ob: Observer | void
  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
  ) {
    ob = new Observer(value)
  }
  if (asRootData && ob) {
    ob.vmCount++
  }
  return ob
}

// 封装Object.defineProperty
export function defineReactive (
  obj: Object,
  key: string,
  val: any,
  customSetter?: ?Function,
  shallow?: boolean
) {
  // defineReactive方法内部的dep,用于收集当前Key的依赖
  const dep = new Dep()

  const property = Object.getOwnPropertyDescriptor(obj, key)
  if (property && property.configurable === false) {
    return
  }

  // 保存原有getter setter
  const getter = property && property.get
  const setter = property && property.set
  if ((!getter || setter) && arguments.length === 2) {
    val = obj[key]
  }

  // 如果val是复杂对象,则转为响应式数据并取出他的'__ob__'上的Observer实例
  let childOb = !shallow && observe(val)
  Object.defineProperty(obj, key, {
    enumerable: true,
    configurable: true,
    get: function reactiveGetter () {
      const value = getter ? getter.call(obj) : val

      // 如果有正在处理的watcher
      if (Dep.target) {
        // 当前key的dep收集watcher
        dep.depend()
        // val的dep收集watcher
        if (childOb) {
          childOb.dep.depend()
          // 最新值如果是数组,数组中的复杂对象也需要收集watcher
          if (Array.isArray(value)) {
            dependArray(value)
          }
        }
      }

      return value
    },
    set: function reactiveSetter (newVal) {
      // 读取旧值
      const value = getter ? getter.call(obj) : val
      // 对比新旧值,无变化则return,无需通知
      if (newVal === value || (newVal !== newVal && value !== value)) {
        return
      }
      if (process.env.NODE_ENV !== 'production' && customSetter) {
        customSetter()
      }
      if (getter && !setter) return
      if (setter) {
        setter.call(obj, newVal)
      } else {
        val = newVal
      }
      // 将新值处理成响应式数据
      childOb = !shallow && observe(newVal)
      // 值发生变化,通知当前key的dep,dep再通知收集的所有watcher
      dep.notify()
    }
  })
}

// 递归,使每层每个复杂对象都能被当前watcher订阅
function dependArray (value: Array<any>) {
  for (let e, i = 0, l = value.length; i < l; i++) {
    e = value[i]
    e && e.__ob__ && e.__ob__.dep.depend()
    if (Array.isArray(e)) {
      dependArray(e)
    }
  }
}

总结:

一、复杂类型的变量会转化成响应式数据,转化为响应式数据的变量都会带有 '__ob__'  属性,所以 '__ob__' 属性可以作为判断响应式数据的标识。

二、变量侦测原理是利用了Object.defineProperty的getter与setter。Object的在getter中收集依赖,在setter中触发依赖。Array在getter中收集依赖,通过重写Array原型方法触发依赖。

三、目前vue这种侦测方案存在缺陷

(1)由于setter方法只能监听的每个key对应的值变化,如果Object新增或者删除一个key, setter是侦测不到,所以不会触发依赖。

...
data() {
  return {
    obj: {
      a: 1;
    }
  }
}
...

this.obj.a = 2; // 触发依赖
this.obj.b = 2; // 不会触发依赖
delete this.obj[a] // 不会触发依赖

(2)由于Array是通过重写Array原型方法触发依赖,所以如果直接修改数组下的元素,是不会触发依赖的。

...
data() {
  return {
    array: [1, 2, 3]
  }
}
...


this.array.push(4); // 触发依赖
this.array[0] = 0; // 不会触发依赖

 针对vue侦测方案的缺陷,vue提供了vm.$set与vm.$del, 这两个API会在方法内调用dep.notify,所以通过API进行赋值可以触发依赖。

具体源码可看:解析vue2.x源码之API $set、$del

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值