Vue异步更新原理

315 阅读4分钟

Vue异步更新队列

Vue高效的秘诀是一套批量,异步的更新策略

108aeeeaecac4eafb82d8317feb1a34.png

  • 事件循环EventLoop:浏览器为了协调事件处理、脚本执行、网络请求和渲染等任务而制定的工作机制
  • 宏任务Task:代表一个个离散的、独立的工作单元。浏览器完成一个宏任务,在下一个宏任务执行开始前,会对页面进行重新渲染。主要包括创建文档对象、解析HTML、执行主线JS代码以及各种事件、
  • 微任务:微任务则是更小的任务,是在当前宏任务执行结束后立即执行的任务。如果存在微任务,浏览器会清空微任务之后在重新渲染。微任务的例子有Promise的回调函数,DOM变化等。 体验一下

Vue中的具体实现

31b3ebee8a14218faac6ce04c7f639c.png

  • 异步:只要监听到数据变化,Vue将开启一个队列,并缓冲在同一事件循环中发生的所有数据变更。
  • 批量:如果一个watcher被多次触发,只会被推入到队列中一次(第一次)。去重对于避免不必要的计算和DOM操作是非常重要的。然后,在下一个事件循环‘tick’中,Vue刷新队列执行实际工作。
  • 异步策略:Vue在内部对异步队列尝试使用原生的Promise.then、MutationObserver或setImmediate,如果执行环境都不支持,则会采用setTimeout代替。

源码

export function defineReactive (
  obj: Object,
  key: string,
  val: any,
  customSetter?: ?Function,
  shallow?: boolean
) {
  //dep和key 1:1
  //key值变化通知更新
  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()  //互相添加映射关系 dep和watcher
        //子Ob实例也要添加映射关系
        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)
      // 每一次的set都会触发dep实例的notify
      dep.notify()
    }
  })
}

当数据改变会触发dep实例的notify方法

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)
    }
    // 遍历关联的所有watcher
    for (let i = 0, l = subs.length; i < l; i++) {
      subs[i].update()
    }
  }

由于watcher和dep互相添加映射关系,notify会遍历数组,实际上遍历的就是watcher,并执行他们的update方法

update () {
    /* istanbul ignore else */

    // 计算属性需要延迟
    if (this.lazy) {
      this.dirty = true
    // sync选项立即执行
    } else if (this.sync) {
      this.run()
    } else {
      // 让watcher入队操作
      queueWatcher(this)
    }
  }

执行queueWatcher方法 让watcher入队。

export function queueWatcher (watcher: Watcher) {
  // 先获取watcher的id
  const id = watcher.id
  // 去重保证单个只会入队一次watcher
  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
      }
      // 异步方式将flushSchedulerQueue放入队列
      nextTick(flushSchedulerQueue)
    }
  }
}

在没有$watch和监听属性下,一个组件只能有一个watcher,queueWatcher会进行去重,然后通过nextTick将flushSchedulerQueue放入队列。

// 此方法就是平时使用的nextTick方法
export function nextTick (cb?: Function, ctx?: Object) {
  let _resolve
  callbacks.push(() => {
    if (cb) {
      try {
        cb.call(ctx)
      } catch (e) {
        handleError(e, ctx, 'nextTick')
      }
    } else if (_resolve) {
      _resolve(ctx)
    }
  })
  if (!pending) {
    pending = true
    // 异步执行callbacks任务
    timerFunc()
  }
  // $flow-disable-line
  if (!cb && typeof Promise !== 'undefined') {
    return new Promise(resolve => {
      _resolve = resolve
    })
  }
}

callbacks是一个普通的数组,将回调函数放入callbacks数组中,然后执行timerFunc方法。

let timerFunc

// The nextTick behavior leverages the microtask queue, which can be accessed
// via either native Promise.then or MutationObserver.
// MutationObserver has wider support, however it is seriously bugged in
// UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
// completely stops working after triggering a few times... so, if native
// Promise is available, we will use it:
/* istanbul ignore next, $flow-disable-line */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
  const p = Promise.resolve()
  timerFunc = () => {
    // 将flushCallbacks放入微任务队列,等待所有同步任务执行完事之后执行
    p.then(flushCallbacks)
    // In problematic UIWebViews, Promise.then doesn't completely break, but
    // it can get stuck in a weird state where callbacks are pushed into the
    // microtask queue but the queue isn't being flushed, until the browser
    // needs to do some other work, e.g. handle a timer. Therefore we can
    // "force" the microtask queue to be flushed by adding an empty timer.
    if (isIOS) setTimeout(noop)
  }
  isUsingMicroTask = true
} else if (!isIE && typeof MutationObserver !== 'undefined' && (
  isNative(MutationObserver) ||
  // PhantomJS and iOS 7.x
  MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
  // Use MutationObserver where native Promise is not available,
  // e.g. PhantomJS, iOS7, Android 4.4
  // (#6466 MutationObserver is unreliable in IE11)
  let counter = 1
  const observer = new MutationObserver(flushCallbacks)
  const textNode = document.createTextNode(String(counter))
  observer.observe(textNode, {
    characterData: true
  })
  timerFunc = () => {
    counter = (counter + 1) % 2
    textNode.data = String(counter)
  }
  isUsingMicroTask = true
} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
  // Fallback to setImmediate.
  // Technically it leverages the (macro) task queue,
  // but it is still a better choice than setTimeout.
  timerFunc = () => {
    setImmediate(flushCallbacks)
  }
} else {
  // Fallback to setTimeout.
  timerFunc = () => {
    setTimeout(flushCallbacks, 0)
  }
}

里面处理了各个平台的兼容处理,当同步任务执行完事后,会执行p.then(flushCallbacks),这里的flushCallbacks就是callbacks数组里全部回调函数的执行

//将callback中的回调全部执行一遍
function flushCallbacks () {
  pending = false
  const copies = callbacks.slice(0)
  callbacks.length = 0
  for (let i = 0; i < copies.length; i++) {
    // 这个位置打一个断点
    copies[i]()
  }
}

数组中的函数就是nexttick方法的参数flushSchedulerQueue。

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.

  // 按照ID的顺序执行watcher的更新
  queue.sort((a, b) => a.id - b.id)

  // do not cache length because more watchers might be pushed
  // as we run existing watchers
  // 按照ID的顺序执行watcher的更新
  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')
  }
}

该方法会按照ID的顺序执行watcher更新,最终会执行watcher.run()方法

run () {
    if (this.active) {
      // 调用watcher的get方法, updateComponent方法
      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) {
          const info = `callback for watcher "${this.expression}"`
          invokeWithErrorHandling(this.cb, this.vm, [value, oldValue], this.vm, info)
        } else {
          this.cb.call(this.vm, value, oldValue)
        }
      }
    }
  }

run方法内部调用了get方法。

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
  }

get方法内部调用了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
        )
      }
    }

getter 就是创建watcher传入的updateComponent方法.

new Watcher(vm, updateComponent, noop, {
    before () {
      if (vm._isMounted && !vm._isDestroyed) {
        callHook(vm, 'beforeUpdate')
      }
    }
  }
let updateComponent
  /* istanbul ignore if */
  if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
    updateComponent = () => {
      const name = vm._name
      const id = vm._uid
      const startTag = `vue-perf-start:${id}`
      const endTag = `vue-perf-end:${id}`

      mark(startTag)
      const vnode = vm._render()
      mark(endTag)
      measure(`vue ${name} render`, startTag, endTag)

      mark(startTag)
      vm._update(vnode, hydrating)
      mark(endTag)
      measure(`vue ${name} patch`, startTag, endTag)
    }
  } else {
    updateComponent = () => {
      vm._update(vm._render(), hydrating)
    }
  }

updateComponent方法执行vm_render,vm._update去执行更新.

举个栗子

        this.foo = Math.random()
        console.log('1:' + this.foo);
        this.foo = Math.random()
        console.log('2:' + this.foo);
        this.foo = Math.random()
        console.log('3:' + this.foo);
        console.log('p1.innerHTML:' + p1.innerHTML)
        this.$nextTick(() => {
          // 这里才是最新的值
          console.log('p1.innerHTML:' + p1.innerHTML)
        })

        // flushCallbacks: [flushScheduleQueue, cb]

最终结果如图: 连续做了3次赋值操作,走了3次dep.notify方法,由于只有一个watcher,所以只走了一次nextTick(flushSchedulerQueue),所以当前flushCallbacks数组内只有一个flushSchedulerQueue更新函数,然后this.$nextTick向flushCallbacks尾部添加了一个回调函数,用于获取浏览器渲染后的结果。所以当前flushCallbacks数组长度为2

28be1243b6031522839f0d7920c832b.png

        // [cb,flushScheduleQueue]
        this.$nextTick(() => {
          // 这里才是最新的值
          console.log('p1.innerHTML:' + p1.innerHTML)
        })
        this.foo = Math.random()
        console.log('1:' + this.foo);
        this.foo = Math.random()
        console.log('2:' + this.foo);
        this.foo = Math.random()
        console.log('3:' + this.foo);
        console.log('p1.innerHTML:' + p1.innerHTML)

最终结果如图: this.nextTick没有做到获取更新后的结果DOM,正常nextTick没有做到获取更新后的结果DOM,正常nextTick是将任务压入当前微任务队列的尾部,但是这种方式,确实先添加了cb,之后才是添加flushScheduleQueue,当cb执行的时候,flushScheduleQueue还没有执行,获取不到更新后的结果。

a95de8211e9a7e109510a16db35b636.png

        this.foo = Math.random()
        console.log('1:' + this.foo);
        this.foo = Math.random()
        console.log('2:' + this.foo);
        this.foo = Math.random()
        console.log('3:' + this.foo);
        // 异步行为,此时内容没变
        console.log('p1.innerHTML:' + p1.innerHTML) // ?
        // [flushCallbacks, cb2]
        // flushCallbacks: [flushScheduleQueue, cb1]
        Promise.resolve().then(() => {
            console.log('promise p1.innerHTML:' + p1.innerHTML)
        })
        this.$nextTick(() => {
            // 这里才是最新的值
            console.log('p1.innerHTML:' + p1.innerHTML) // ?
        })

最终结果如图:

promise.resolve().then()也是一个微任务,会想微任务队列中添加,当前的flushCallbacks是[flushScheduleQueue, cb1]组成的微任务队列,然后promise.resolve().then()向当前事件循环内添加微任务, [flushCallbacks, cb2],他是通过和flushCallbacks数组新组成了个微任务队列。

2f3c9a94ee96eafc086bdae5c35b9d3.png