结合源码聊一聊Vue的响应式原理__Vue.js
发布于 3 年前 作者 banyungong 1106 次浏览 来自 分享
粉丝福利 : 关注VUE中文社区公众号,回复视频领取粉丝福利
Vue通过响应式设计实现了数据的双向绑定,能够做到页面数据的动态更新。我们都知道Vue实现响应式的核心是 Object.defineProperty(),但是具体是如何实现的?相信很多人都是不清楚的。这篇文章我们就结合Vue源码来了解一下响应式的实现方式。

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

1、数据劫持(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()。

2、依赖收集

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知道通知哪些订阅进行更新。这也就到了下一阶段:派发更新。

3、派发更新

经过第二部分,页面渲染完成后,也完成了依赖的收集。后面如果数据发生变化,会触发第一步对数据定义的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,从而触发组件的重新渲染。

再看一遍这个图,是不是感觉好像看明白了~

4、挖个坑

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

Vue3 实现响应式的方式改为使用 Proxy,具体的实现这篇文章留个坑,下一篇来填。如果还不了解 Proxy 的同学可以先去看一看介绍:MDN-Proxy

版权声明:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 作者: 猿叨叨 原文链接:https://juejin.im/post/6847902215395360775

回到顶部