欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

深入理解Vue nextTick 机制

程序员文章站 2022-05-20 09:45:55
我们先来看一段vue的执行代码: export default { data () { return { msg: 0 } },...

我们先来看一段vue的执行代码:

export default {
 data () {
  return {
   msg: 0
  }
 },
 mounted () {
  this.msg = 1
  this.msg = 2
  this.msg = 3
 },
 watch: {
  msg () {
   console.log(this.msg)
  }
 }
}

这段脚本执行我们猜测1000m后会依次打印:1、2、3。但是实际效果中,只会输出一次:3。为什么会出现这样的情况?我们来一探究竟。

queuewatcher

我们定义 watch 监听 msg ,实际上会被vue这样调用 vm.$watch(keyorfn, handler, options) 。 $watch 是我们初始化的时候,为 vm 绑定的一个函数,用于创建 watcher 对象。那么我们看看 watcher 中是如何处理 handler 的:

this.deep = this.user = this.lazy = this.sync = false
...
 update () {
  if (this.lazy) {
   this.dirty = true
  } else if (this.sync) {
   this.run()
  } else {
   queuewatcher(this)
  }
 }
...

初始设定 this.deep = this.user = this.lazy = this.sync = false ,也就是当触发 update 更新的时候,会去执行 queuewatcher 方法:

const queue: array<watcher> = []
let has: { [key: number]: ?true } = {}
let waiting = false
let flushing = false
...
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
   nexttick(flushschedulerqueue)
  }
 }
}

这里面的 nexttick(flushschedulerqueue) 中的 flushschedulerqueue 函数其实就是 watcher 的视图更新:

function flushschedulerqueue () {
 flushing = true
 let watcher, id
 ...
 for (index = 0; index < queue.length; index++) {
  watcher = queue[index]
  id = watcher.id
  has[id] = null
  watcher.run()
  ...
 }
}

另外,关于 waiting 变量,这是很重要的一个标志位,它保证 flushschedulerqueue 回调只允许被置入 callbacks 一次。 接下来我们来看看 nexttick 函数,在说 nextick 之前,需要你对 event loop 、 microtask 、 macrotask 有一定的了解,vue nexttick 也是主要用到了这些基础原理。如果你还不了解,可以参考我的这篇文章 event loop 简介 好了,下面我们来看一下他的实现:

export const nexttick = (function () {
 const callbacks = []
 let pending = false
 let timerfunc

 function nexttickhandler () {
  pending = false
  const copies = callbacks.slice(0)
  callbacks.length = 0
  for (let i = 0; i < copies.length; i++) {
   copies[i]()
  }
 }

 // an asynchronous deferring mechanism.
 // in pre 2.4, we used to use microtasks (promise/mutationobserver)
 // but microtasks actually has too high a priority and fires in between
 // supposedly sequential events (e.g. #4521, #6690) or even between
 // bubbling of the same event (#6566). technically setimmediate should be
 // the ideal choice, but it's not available everywhere; and the only polyfill
 // that consistently queues the callback after all dom events triggered in the
 // same loop is by using messagechannel.
 /* istanbul ignore if */
 if (typeof setimmediate !== 'undefined' && isnative(setimmediate)) {
  timerfunc = () => {
   setimmediate(nexttickhandler)
  }
 } else if (typeof messagechannel !== 'undefined' && (
  isnative(messagechannel) ||
  // phantomjs
  messagechannel.tostring() === '[object messagechannelconstructor]'
 )) {
  const channel = new messagechannel()
  const port = channel.port2
  channel.port1.onmessage = nexttickhandler
  timerfunc = () => {
   port.postmessage(1)
  }
 } else
 /* istanbul ignore next */
 if (typeof promise !== 'undefined' && isnative(promise)) {
  // use microtask in non-dom environments, e.g. weex
  const p = promise.resolve()
  timerfunc = () => {
   p.then(nexttickhandler)
  }
 } else {
  // fallback to settimeout
  timerfunc = () => {
   settimeout(nexttickhandler, 0)
  }
 }

 return function queuenexttick (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
   timerfunc()
  }
  // $flow-disable-line
  if (!cb && typeof promise !== 'undefined') {
   return new promise((resolve, reject) => {
    _resolve = resolve
   })
  }
 }
})()

首先vue通过 callback 数组来模拟事件队列,事件队里的事件,通过 nexttickhandler 方法来执行调用,而何事进行执行,是由 timerfunc 来决定的。我们来看一下 timefunc 的定义:

if (typeof setimmediate !== 'undefined' && isnative(setimmediate)) {
  timerfunc = () => {
   setimmediate(nexttickhandler)
  }
 } else if (typeof messagechannel !== 'undefined' && (
  isnative(messagechannel) ||
  // phantomjs
  messagechannel.tostring() === '[object messagechannelconstructor]'
 )) {
  const channel = new messagechannel()
  const port = channel.port2
  channel.port1.onmessage = nexttickhandler
  timerfunc = () => {
   port.postmessage(1)
  }
 } else
 /* istanbul ignore next */
 if (typeof promise !== 'undefined' && isnative(promise)) {
  // use microtask in non-dom environments, e.g. weex
  const p = promise.resolve()
  timerfunc = () => {
   p.then(nexttickhandler)
  }
 } else {
  // fallback to settimeout
  timerfunc = () => {
   settimeout(nexttickhandler, 0)
  }
 }

可以看出 timerfunc 的定义优先顺序 macrotask --> microtask ,在没有 dom 的环境中,使用 microtask ,比如weex

setimmediate、messagechannel vs settimeout

我们是优先定义 setimmediate 、 messagechannel 为什么要优先用他们创建macrotask而不是settimeout? html5中规定settimeout的最小时间延迟是4ms,也就是说理想环境下异步回调最快也是4ms才能触发。vue使用这么多函数来模拟异步任务,其目的只有一个,就是让回调异步且尽早调用。而messagechannel 和 setimmediate 的延迟明显是小于settimeout的。

解决问题

有了这些基础,我们再看一遍上面提到的问题。因为 vue 的事件机制是通过事件队列来调度执行,会等主进程执行空闲后进行调度,所以先回去等待所有的进程执行完成之后再去一次更新。这样的性能优势很明显,比如:

现在有这样的一种情况,mounted的时候test的值会被++循环执行1000次。 每次++时,都会根据响应式触发 setter->dep->watcher->update->run 。 如果这时候没有异步更新视图,那么每次++都会直接操作dom更新视图,这是非常消耗性能的。 所以vue实现了一个 queue 队列,在下一个tick(或者是当前tick的微任务阶段)的时候会统一执行 queue 中 watcher 的run。同时,拥有相同id的watcher不会被重复加入到该queue中去,所以不会执行1000次watcher的run。最终更新视图只会直接将test对应的dom的0变成1000。 保证更新视图操作dom的动作是在当前栈执行完以后下一个tick(或者是当前tick的微任务阶段)的时候调用,大大优化了性能。

有趣的问题

var vm = new vue({
  el: '#example',
  data: {
    msg: 'begin',
  },
  mounted () {
   this.msg = 'end'
   console.log('1')
   settimeout(() => { // macrotask
     console.log('3')
   }, 0)
   promise.resolve().then(function () { //microtask
    console.log('promise!')
   })
   this.$nexttick(function () {
    console.log('2')
   })
 }
})

这个的执行顺序想必大家都知道先后打印:1、promise、2、3。

  1. 因为首先触发了 this.msg = 'end' ,导致触发了 watcher 的 update ,从而将更新操作callback push进入vue的事件队列。
  2. this.$nexttick 也为事件队列push进入了新的一个callback函数,他们都是通过 setimmediate --> messagechannel --> promise --> settimeout 来定义 timefunc 。而 promise.resolve().then 则是microtask,所以会先去打印promise。
  3. 在支持 messagechannel 和 setimmediate 的情况下,他们的执行顺序是优先于 settimeout 的(在ie11/edge中,setimmediate延迟可以在1ms以内,而settimeout有最低4ms的延迟,所以setimmediate比settimeout(0)更早执行回调函数。其次因为事件队列里,优先收入callback数组)所以会打印2,接着打印3
  4. 但是在不支持 messagechannel 和 setimmediate 的情况下,又会通过 promise 定义 timefunc ,也是老版本vue 2.4 之前的版本会优先执行 promise 。这种情况会导致顺序成为了:1、2、promise、3。因为this.msg必定先会触发dom更新函数,dom更新函数会先被callback收纳进入异步时间队列,其次才定义 promise.resolve().then(function () { console.log('promise!')}) 这样的microtask,接着定义 $nexttick 又会被callback收纳。我们知道队列满足先进先出的原则,所以优先去执行callback收纳的对象。

后记

如果你对vue源码感兴趣,可以来这里:更多好玩的vue约定源码解释

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。