结合源码聊一聊Vue的响应式原理

Vue经过响应式设计实现了数据的双向绑定,可以作到页面数据的动态更新。咱们都知道Vue实现响应式的核心是 Object.defineProperty(),可是具体是如何实现的?相信不少人都是不清楚的。这篇文章咱们就结合Vue源码来了解一下响应式的实现方式。

Vue的响应式实现方式能够分为三个主要部分:数据劫持(observe)、依赖收集并注册观察者(watcher)、派发更新。

一、数据劫持(Object.defineProperty() )

数据劫持就是对数据的读写操做进行监听,也只有这样,Vue才能知道咱们的数据修改了,它须要更新DOM;或者是用户输入内容了,它须要更新对应的变量。
在说数据劫持的实现以前,咱们先来了解一下 Object.defineProperty() 属性,由于这个属性是Vue2 实现响应式的核心原理。

Object.defineProperty()

Object.definProperty(obj, prop, descriptor)
这个方法的做用是直接在目标对象上定义一个新的属性,或者修改目标对象的现有属性,而后返回这个对象。

let obj = {}
Object.defineProperty(obj, 'name', {
    value: '猿叨叨'
})
obj // {name: '猿叨叨'}复制代码

可是这个方法的做用远不止这些,它的 descriptor 参数接收的是一个对象,给出了不少能够配置的属性,具体你们能够自行查看 MDN文档 。咱们今天只关心它的存取描述符 get 和 set,get 在读取目标对象属性时会被调用,set 在修改目标对象属性值时会被调用。经过这两个描述符,咱们能够实现对象属性的监听,并在其中进行一些操做。

let obj = {}
let midValue
Object.defineProperty(obj, 'name', {
    get(){
        console.log('获取name的值')
        return midValue
    },
    set(val){
        console.log('设置name')
        midValue = val
    }
})
obj.name = '猿叨叨'  //设置name '猿叨叨'
obj.name  //获取name的值 '猿叨叨'复制代码

initState()

在上一篇文章 《 结合源码聊一聊Vue的生命周期》中,咱们提到在created以前会执行 initState (点击能够查看该方法源码)方法,该方法主要是初始化props、methods、data等内容,今天咱们只关心data。

initData()

data的初始化调用了 initData 方法,咱们来看一下这个方法的源码。

function initData (vm: Component) {
  let data = vm.$options.data
  data = vm._data = typeof data === 'function'
    ? getData(data, vm)
    : data || {}
  if (!isPlainObject(data)) {
    data = {}
    process.env.NODE_ENV !== 'production' && warn(
      'data functions should return an object:\n' +
      'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
      vm
    )
  }
  // proxy data on instance
  const keys = Object.keys(data)
  const props = vm.$options.props
  const methods = vm.$options.methods
  let i = keys.length
  while (i--) {
    const key = keys[i]
    if (process.env.NODE_ENV !== 'production') {
      if (methods && hasOwn(methods, key)) {
        warn(
          `Method "${key}" has already been defined as a data property.`,
          vm
        )
      }
    }
    if (props && hasOwn(props, key)) {
      process.env.NODE_ENV !== 'production' && warn(
        `The data property "${key}" is already declared as a prop. ` +
        `Use prop default value instead.`,
        vm
      )
    } else if (!isReserved(key)) {
      proxy(vm, `_data`, key)
    }
  }
  // observe data
  observe(data, true /* asRootData */)
}复制代码

这个函数首先获取到组件的data数据,而后对data进行一系列的判断:data返回值必须是对象,data中变量的命名不能与props、methods重名,不能是保留字段等。这些条件都知足之后执行 proxy() 方法,最后对整个 data 执行 observe() 方法,接下来咱们分别看这两个方法都干了些什么。

proxy()

const sharedPropertyDefinition = {
  enumerable: true,
  configurable: true,
  get: noop,
  set: noop
}
export function proxy (target: Object, sourceKey: string, key: string) {
  sharedPropertyDefinition.get = function proxyGetter () {
    return this[sourceKey][key]
  }
  sharedPropertyDefinition.set = function proxySetter (val) {
    this[sourceKey][key] = val
  }
  Object.defineProperty(target, key, sharedPropertyDefinition)
}复制代码

这个函数的逻辑很简单,经过 Object.defineProperty() 方法将属性代理到 vm 实例上,这样咱们 vm.xxx 读写到自定义的数据,也就是在读写 vm._data.xxx。

observe()

/** * Attempt to create an observer instance for a value, * returns the new observer if successfully observed, * or the existing observer if the value already has one. */
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
}复制代码

observe() 方法使用来检测数据的变化,它首先判断传入的参数是对象而且不是 VNode,不然直接返回,而后判断当前对象是否存在 __ob__ 属性,若是不存在而且传入的对象知足一系列条件,则经过 Observe 类实例化一个 __ob__。那么接下来咱们就要看 Observe 类的逻辑了。

Observe

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
    this.dep = new Dep()
    this.vmCount = 0
    def(value, '__ob__', this)
    if (Array.isArray(value)) {
      if (hasProto) {
        protoAugment(value, arrayMethods)
      } else {
        copyAugment(value, arrayMethods, arrayKeys)
      }
      this.observeArray(value)
    } else {
      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) {
    for (let i = 0, l = items.length; i < l; i++) {
      observe(items[i])
    }
  }
}复制代码

咱们来看一下 Observe 类中构造函数的逻辑:
  • 首先是实例化 Dep(),Dep主要是用来管理依赖的,咱们下一部分再详细展开。
  • 而后经过 def() 把当前组件实例添加到 data数据对象 的 __ob__ 属性上
  • 对传入的value进行分类处理,若是是数组,则调用 observeArray() 方法;若是是对象,则调用 walk()。
walk() 方法对传入的对象进行遍历,而后对每一个属性调用 defineReactive() 方法;observeArray() 方法遍历传入的数组,对每一个数组元素调用 observe() 方法,最终仍是会对每一个元素执行walk()方法。

defineReactive()

/** * Define a reactive property on an Object. */
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()
      }
      // #7981: for accessor properties without setter
      if (getter && !setter) return
      if (setter) {
        setter.call(obj, newVal)
      } else {
        val = newVal
      }
      childOb = !shallow && observe(newVal)
      dep.notify()
    }
  })
}复制代码

这个函数首先初始化 Dep;而后经过 Object.getOwnPropertyDescriptor 方法拿到传入对象属性的描述符;通过判断后对子对象递归调用 observe 方法,从而作到无论对象层次有多深均可以保证遍历到每个属性并将其变成响应式属性。

若是调用data的某个属性,就会触发 getter,而后经过 dep 进行依赖收集,具体流程咱们后面进行分析;当有属性发生改变,会调用 setter 方法,而后经过 dep 的 notify 方法通知更新依赖数据的DOM结构。

总结

这个阶段主要的做用就是将数据所有转换为响应式属性,能够简单地归纳成:
  • 在生命周期 beforeCreate 以后,created以前进行用户数据初始化时,执行initData初始化data数据,initData调用proxy和observe
  • proxy 将数据代理到组件实例上,vm._data.xxx → vm.xxx
  • observe 调用 Observe 类对属性进行遍历,而后调用 defineReactive
  • defineReactive 将属性定义为 getter和setter。getter中调用 dep.depend();setter中调用 dep.notify()。

二、依赖收集

Dep

前面遇到了 Dep 类的实例化,而且调用了里边的 depend 和 notify 等方法,接下来咱们就看一下 Dep 类里面作了什么。

/** * A dep is an observable that can have multiple * directives subscribing to it. */
export default class Dep {
  static target: ?Watcher;
  id: number;
  subs: Array;

  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()
    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
      subs.sort((a, b) => a.id - b.id)
    }
    for (let i = 0, l = subs.length; i < l; i++) {
      subs[i].update()
    }
  }
}复制代码

Dep类主要初始化了 id 和 subs,其中 subs 是用来存储 Watcher 的数组。另外,Dep 还有一个静态属性 target,它也是 Watcher 类型,而且全局惟一,表示的是当前正在被计算的 Watcher。除此以外,它还有一些方法:addSub用来往 subs 数组里插入 Watcher;removeSub用来从 subs 中移除;depend调用的是 Watcher 的addDep方法;notify会对subs中的元素进行排序(在条件知足的状况下),而后进行遍历,调用每一个 Watcher 的update方法。

从上面咱们能够看出来,Dep类其实就是对Watcher进行管理的,因此接下来咱们看看Watcher里都作了哪些事情。

Watcher

let uid = 0

/** * A watcher parses an expression, collects dependencies, * and fires callback when the expression value changes. * This is used for both the $watch() api and directives. */
export default class Watcher {
  //...

  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.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 // uid for batching
    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()
      : ''
    // parse expression for getter
    if (typeof expOrFn === 'function') {
      this.getter = expOrFn
    } else {
      this.getter = parsePath(expOrFn)
      if (!this.getter) {
        this.getter = 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
        )
      }
    }
    this.value = this.lazy
      ? undefined
      : 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
  }
}复制代码

watch实例有两种类型,一直是咱们经常使用的自定义watch,还有一种是Render类型。在上一篇文章了解生命周期时,mounted 阶段有一段这样的代码:

// we set this to vm._watcher inside the watcher's constructor
  // since the watcher's initial patch may call $forceUpdate (e.g. inside child
  // component's mounted hook), which relies on vm._watcher being already defined
  new Watcher(vm, updateComponent, noop, {
    before () {
      if (vm._isMounted && !vm._isDestroyed) {
        callHook(vm, 'beforeUpdate')
      }
    }
  }, true /* isRenderWatcher */)复制代码

这里实例化了一个渲染watcher,对组件进行监听。咱们来看一下watcher实例化的过程:

进入Watcher的构造函数后,通过初始化参数和一些属性之后,执行 get() 方法,get主要有如下几步:
这个方法就是把当前正在渲染的 Watcher 赋值给Dep的target属性,并将其压入 targetStack 栈。

export function pushTarget (target: ?Watcher) {
  targetStack.push(target)
  Dep.target = target
}复制代码

  • 接下来在 try catch 中执行了下面的代码:

value = this.getter.call(vm, vm)复制代码

this.getter,调用的是建立 Watcher 时传入的回调函数,也就是在实例化 Watcher 时传入的 updateComponent ,而这个方法执行的是 vm._update(vm._render(), hydrating) , vm._render 会将代码渲染为 VNode,这个过程势必是要访问组件实例上的数据的,在访问数据的过程也就触发了数据的 getter。从 defineReactive 方法中咱们知道 getter 会调用 dep.depend() 方法,继而执行Dep.target.addDep(this) ,由于 Dep.target 拿到的是要渲染的 watcher 实例,因此也就是调用当前要渲染 watcher 实例的 addDep() 方法。
  • addDep

/** * 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)
      }
    }
  }复制代码

addDep() 首先进行判断,保证当前数据所持有 dep 实例的 subs 数组中不存在当前 watcher 实例,而后执行 dep.addSub(),将当前 watcher 实例加入当前数据所持有的的 dep 实例的 subs 数组中,为后续数据变化是更新DOM作准备。


至此已经完成了一轮的依赖收集,可是后面在 finally 还有一些逻辑:

// "touch" every property so they are all tracked as
// dependencies for deep watching
if (this.deep) {
    traverse(value)
}
popTarget()
this.cleanupDeps()复制代码

  • 首先对若是deep参数为true,就对 value 进行递归访问,以保证可以触发每一个子项的 getter 做为依赖进行记录。
  • 执行 popTarget() 
这一步是在依赖收集完成后,将完成的 watcher 实例弹出 targetStack 栈,同时将 Dep.target 恢复成上一个状态。

export function popTarget () {
  targetStack.pop()
  Dep.target = targetStack[targetStack.length - 1]
}复制代码

  • 执行 this.cleanupDeps()
整理并移除不须要的依赖

/** * 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
  }复制代码

总结

这个阶段主要是对依赖某个数据的组件信息进行收集,也能够理解为创建数据和组件之间的对应关系,以便在数据变化时知道哪些组件须要更新。该过程能够简单地总结为如下步骤:
  • 在create阶段完成data数据初始化之后进入mount阶段,此阶段会建立 渲染类型的watcher实例监听 vm 变化,回调函数为 updateComponent;watcher实例化的过程当中完成了 dep.target 的赋值,同时触发传入的回调函数。
  • updateComponent 被触发,回调函数内部执行 vm._update(vm._render(), hydrating),vm._render() 会将代码渲染为 VNode。
  • 代码渲染为 VNode 的过程,会涉及到数据的访问,势必会触发上一节定义的数据的 getter,getter中调用 dep.depend(),进而调用 watcher.addDep(),最终调用到 dep.addSub 将watcher实例放入 subs 数组。
至此依赖收集的过程已经完成,当数据发生改变时,Vue能够经过subs知道通知哪些订阅进行更新。这也就到了下一阶段:派发更新。

三、派发更新

通过第二部分,页面渲染完成后,也完成了依赖的收集。后面若是数据发生变化,会触发第一步对数据定义的setter,咱们再来看一下 setter 的逻辑:

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()
  }
  // #7981: for accessor properties without setter
  if (getter && !setter) return
  if (setter) {
    setter.call(obj, newVal)
  } else {
    val = newVal
  }
  childOb = !shallow && observe(newVal)
  dep.notify()
}复制代码

在 setter 最后,调用了 dep.notify(),上一节在看 Dep 类的源码时咱们知道,notify 方法会调用subs数组中每一个 watcher 实例的 update 方法。

/** * Subscriber interface. * Will be called when a dependency changes. */
  update () {
    /* istanbul ignore else */
    if (this.lazy) {
      this.dirty = true
    } else if (this.sync) {
      this.run()
    } else {
      queueWatcher(this)
    }
  }复制代码

上述代码中,lazy 和 sync 两种状况本文不展开详说,大部分数据更新时走的是最后else分支,执行 queueWatcher() 方法,接下来咱们看一下这个方法的代码:

queueWatcher() 

/** * Push a watcher into the watcher queue. * Jobs with duplicate IDs will be skipped unless it's * pushed when the queue is being flushed. */
export function queueWatcher (watcher: Watcher) {
  const id = watcher.id
  if (has[id] == null) {
    has[id] = true
    if (!flushing) {
      queue.push(watcher)
    } else {
      // if already flushing, splice the watcher based on its id
      // if already past its id, it will be run next immediately.
      let i = queue.length - 1
      while (i > index && queue[i].id > watcher.id) {
        i--
      }
      queue.splice(i + 1, 0, watcher)
    }
    // queue the flush
    if (!waiting) {
      waiting = true

      if (process.env.NODE_ENV !== 'production' && !config.async) {
        flushSchedulerQueue()
        return
      }
      nextTick(flushSchedulerQueue)
    }
  }
}复制代码

这个函数引入了队列的概念,用来存储等待更新的 watcher 实例,由于Vue并不会每次数据改变都触发 watcher 回调,存入队列后,在 nextTick 后执行。
在函数最开始,经过has判断保证每一个 watcher 在队列里只会被添加一次;而后判断 flushing ,这个值在调用 flushSchedulerQueue 方法时,会置为 true,所以这个值能够用来判断当前是否处于正在执行 watcher 队列的状态中,根据这个值,分为两种状况:
  1. 当 flushing 为false,直接将watcher塞入队列中。
  2. flushing 为true,证实当前队列正在执行,此时从队列尾部往前找,找到一个待插入队列watcher的id比当前队列中watcher的id大的位置,而后将它插入到找到的watcher后面。
执行完上述判断逻辑后,经过waiting判断会否能够继续往下执行,waiting在最外层被初始化为false,进入if内部,被置为true,而且在队列执行完毕进行reset以前不会改变。这样能够保证每一个队列只会执行一次更新逻辑。更新调用的是 flushSchedulerQueue 方法:

flushSchedulerQueue()

/** * Flush both queues and run the watchers. */
function flushSchedulerQueue () {
  currentFlushTimestamp = getNow()
  flushing = true
  let watcher, id

  // Sort queue before flush.
  // This ensures that:
  // 1. Components are updated from parent to child. (because parent is always
  // created before the child)
  // 2. A component's user watchers are run before its render watcher (because
  // user watchers are created before the render watcher)
  // 3. If a component is destroyed during a parent component's watcher run,
  // its watchers can be skipped.
  queue.sort((a, b) => a.id - b.id)

  // do not cache length because more watchers might be pushed
  // as we run existing watchers
  for (index = 0; index < queue.length; index++) {
    watcher = queue[index]
    if (watcher.before) {
      watcher.before()
    }
    id = watcher.id
    has[id] = null
    watcher.run()
    // in dev build, check and stop circular updates.
    if (process.env.NODE_ENV !== 'production' && has[id] != null) {
      circular[id] = (circular[id] || 0) + 1
      if (circular[id] > MAX_UPDATE_COUNT) {
        warn(
          'You may have an infinite update loop ' + (
            watcher.user
              ? `in watcher with expression "${watcher.expression}"`
              : `in a component render function.`
          ),
          watcher.vm
        )
        break
      }
    }
  }
  // keep copies of post queues before resetting state
  const activatedQueue = activatedChildren.slice()
  const updatedQueue = queue.slice()

  resetSchedulerState()

  // call component updated and activated hooks
  callActivatedHooks(activatedQueue)
  callUpdatedHooks(updatedQueue)

  // devtool hook
  /* istanbul ignore if */
  if (devtools && config.devtools) {
    devtools.emit('flush')
  }
}复制代码

更新方法首先会将flushing 置为true,而后对 watcher 队列进行排序,根据注释能够知道要保证如下三个条件:
  • 更新从父到子,由于建立是从父到子,所以父组件的 watcher 要比子组件先建立
  • 用户自定义的watcher要先于渲染watcher执行
  • 当某个组件在其父组件 watcher 执行期间被销毁了,那么这个组件的watcher能够跳过不执行
排序完成后,对队列进行遍历,这里须要注意的是,遍历时不能缓存队列的长度,由于在遍历过程当中可能会有新的watcher插入,此时flushing为true,会执行上一个方法中咱们分析的第二种状况。而后若是watcher存在before参数,先执行before对应的方法;以后执行watcher的run方法。再日后就是对死循环的判断;最后就是队列遍历完后对一些状态变量初始化,由resetSchedulerState方法完成。
咱们看一下 watcher 的 run 方法:

watcher.run()

/** * Scheduler job interface. * Will be called by the scheduler. */
  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)
        }
      }
    }
  }复制代码

run方法首先经过 this.get() 拿到新值,而后进行判断,若是知足新值不等于旧值、新值是一个对象或者deep模式任何一个条件,则执行 watcher 的回调函数,并将新值和旧值分别做为第一个和第二个参数,这也是为何咱们在使用watcher时总能拿到新值和旧值的缘由。

若是是渲染类型的watcher,在run方法中执行 this.get() 求值是,会触发 getter 方法,拿到新值后,会调用watcher的回调函数 updateComponent,从而触发组件的从新渲染。

总结

这个阶段主要是当数据发生变化时,如何通知到组件进行更新,能够简单总结为如下几个步骤:
  • 当数据发生变化,会触发数据的 setter,setter 中调用了 dep.notify。
  • dep.notify 中遍历依赖收集阶段获得的 subs 数组,并调用每一个watcher元素的 update 方法。
  • update 中调用 queueWatcher 方法,该方法整理传入的watcher实例,并生成 watcher 队列,而后调用 flushSchedulerQueue 方法。
  • flushSchedulerQueue 完成对 watcher 队列中元素的排序(先父后子,先自定义后render,子组件销毁可调过次watcher),排序完成后遍历队列,调用每一个watcher的 run 方法。
  • run 方法中调用 this.get() 获得数据新值,而后调用watcher的回调函数,渲染类watcher为 updateComponent,从而触发组件的从新渲染。


再看一遍这个图,是否是感受好像看明白了~javascript

四、挖个坑

到这里Vue的响应式原理基本已经结束了,可是相信大多数人也都据说过,Vue3 响应式实现的方式再也不使用 Object.definePeoperty。缘由咱们也知道,Vue是在初始化阶段经过转换setter/getter完成的响应式,因此没有办法检测到初始化之后新增的对象属性;同时不能检测经过下标对数组元素的修改。

Vue3 实现响应式的方式改成使用 Proxy,具体的实现这篇文章留个坑,下一篇来填。若是还不了解 Proxy 的同窗能够先去看一看介绍: MDN-Proxy
相关文章
相关标签/搜索