深入理解Vue nextTick 机制


Posted in Javascript onApril 28, 2018

我们先来看一段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约定源码解释

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

Javascript 相关文章推荐
Javascript 检测、添加、移除样式(className)函数代码
Sep 08 Javascript
JavaScript 设计模式 富有表现力的Javascript(一)
May 26 Javascript
JQuery中使用Ajax赋值给全局变量失败异常的解决方法
Aug 18 Javascript
jQuery实现鼠标滚轮动态改变样式或效果
Jan 05 Javascript
js命名空间写法示例
Dec 18 Javascript
JavaScript 函数的定义-调用、注意事项
Apr 16 Javascript
BootStrap Table 后台数据绑定、特殊列处理、排序功能
May 27 Javascript
总结javascript三元运算符知识点
Sep 28 Javascript
socket io与vue-cli的结合使用的示例代码
Nov 01 Javascript
使用vue cli4.x搭建vue项目的过程详解
May 08 Javascript
vue-cli3访问public文件夹静态资源报错的解决方式
Sep 02 Javascript
vue-router中hash模式与history模式的区别
Jun 23 Vue.js
jQuery实现的电子时钟效果完整示例
Apr 28 #jQuery
vue+jquery+lodash实现滑动时顶部悬浮固定效果
Apr 28 #jQuery
Vue实现PopupWindow组件详解
Apr 28 #Javascript
详解angular路由高亮之RouterLinkActive
Apr 28 #Javascript
vue弹窗组件使用方法
Apr 28 #Javascript
学习Vue组件实例
Apr 28 #Javascript
vue弹窗消息组件的使用方法
Sep 24 #Javascript
You might like
PHP中最容易忘记的一些知识点总结
2013/04/28 PHP
Extjs gridpanel 出现横向滚动条问题的解决方法
2011/07/04 Javascript
基于JQuery实现的类似购物商城的购物车
2011/12/06 Javascript
判断js对象是否拥有某一个属性的js代码
2013/08/16 Javascript
js动态拼接正则表达式的两种方法
2014/03/04 Javascript
js实现图片在未加载完成前显示加载中字样
2014/09/03 Javascript
jquery增加和删除元素的方法
2015/01/14 Javascript
window.onerror()的用法与实例分析
2016/01/27 Javascript
jQuery实现内容定时切换效果完整实例
2016/04/06 Javascript
JavaScript reduce和reduceRight详解
2016/10/24 Javascript
Jquery Easyui自定义下拉框组件使用详解(21)
2020/12/31 Javascript
javascript ASCII和Hex互转的实现方法
2016/12/27 Javascript
微信小程序 MinUI组件库系列之badge徽章组件示例
2018/08/20 Javascript
微信小程序简单的canvas裁剪图片功能详解
2019/07/12 Javascript
微信小程序设置滚动条过程详解
2019/07/25 Javascript
基于js实现复制内容到操作系统粘贴板过程解析
2019/10/11 Javascript
js操作两个json数组合并、去重,以及删除某一项元素
2020/09/22 Javascript
Python求两个list的差集、交集与并集的方法
2014/11/01 Python
使用Python的Bottle框架写一个简单的服务接口的示例
2015/08/25 Python
Python while 循环使用的简单实例
2016/06/08 Python
Python端口扫描简单程序
2016/11/10 Python
python利用拉链法实现字典方法示例
2017/03/25 Python
一个基于flask的web应用诞生 组织结构调整(7)
2017/04/11 Python
python遍历文件夹下所有excel文件
2018/01/03 Python
详解django中url路由配置及渲染方式
2019/02/25 Python
python中的global关键字的使用方法
2019/08/20 Python
Django异步任务线程池实现原理
2019/12/17 Python
Python pyautogui模块实现鼠标键盘自动化方法详解
2020/02/17 Python
Python matplotlib画图时图例说明(legend)放到图像外侧详解
2020/05/16 Python
Python调用JavaScript代码的方法
2020/10/27 Python
html5 canvas移动浏览器上实现图片压缩上传
2016/03/11 HTML / CSS
法律专业个人实习自我鉴定
2013/09/23 职场文书
社区维稳工作方案
2014/06/06 职场文书
见习报告的格式
2014/11/04 职场文书
幼儿园辞职书
2015/02/26 职场文书
Java中常用解析工具jackson及fastjson的使用
2021/06/28 Java/Android