Vue nextTick 机制
背景
我们先来看一段Vue的执行代码:
export default {
  data () {
    return {
      msg: 0
    }
  },
  mounted () {
    this.msg = 1
    this.msg = 2
    this.msg = 3
  },
  watch: {
    msg () {
      console.log(this.msg)
    }
  }
}
这段脚本执行我们猜测会依次打印: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。
因为首先触发了
this.msg = 'end',导致触发了watcher的update,从而将更新操作callback push进入vue的事件队列。this.$nextTick也为事件队列push进入了新的一个callback函数,他们都是通过setImmediate-->MessageChannel-->Promise-->setTimeout来定义timeFunc。而Promise.resolve().then则是microTask,所以会先去打印promise。在支持
MessageChannel和setImmediate的情况下,他们的执行顺序是优先于setTimeout的(在IE11/Edge中,setImmediate延迟可以在1ms以内,而setTimeout有最低4ms的延迟,所以setImmediate比setTimeout(0)更早执行回调函数。其次因为事件队列里,优先收入callback数组)所以会打印2,接着打印3但是在不支持
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源码】Vue中DOM的异步更新策略以及nextTick机制
Vue nextTick 机制的更多相关文章
- vue nextTick使用
		
Vue nextTick使用 vue生命周期 原因是在created()钩子函数执行的时候DOM 其实并未进行任何渲染,而此时进行DOM操作无异于徒劳,所以此处一定要将DOM操作的js代码放进Vue. ...
 - 全面解析Vue.nextTick实现原理
		
vue中有一个较为特殊的API,nextTick.根据官方文档的解释,它可以在DOM更新完毕之后执行一个回调,用法如下: // 修改数据 vm.msg = 'Hello' // DOM 还没有更新 V ...
 - Vue源码阅读一:说说vue.nextTick实现
		
用法: 在下次 DOM 更新循环结束之后执行延迟回调.在修改数据之后立即使用这个方法,获取更新后的 DOM. 疑惑: 怎么实现的延迟回调 原理: JavaScript语言的一大特点就是单线程,同一个时 ...
 - Vue.nextTick 的原理和用途
		
转载自https://segmentfault.com/a/1190000012861862 概览 官方文档说明: 用法: 在下次 DOM 更新循环结束之后执行延迟回调.在修改数据之后立即使用这个方法 ...
 - 总结了一下 Vue.nextTick() 的原理和用途
		
对于 Vue.nextTick 方法,自己有些疑惑.在查询了各种资料后,总结了一下其原理和用途,如有错误,请不吝赐教. 概览 官方文档说明: 用法: 在下次 DOM 更新循环结束之后执行延迟回调.在修 ...
 - 【转载】Vue.nextTick 的原理和用途
		
对于 Vue.nextTick 方法,自己有些疑惑.在查询了各种资料后,总结了一下其原理和用途,如有错误,请不吝赐教. 概览 官方文档说明: 用法: 在下次 DOM 更新循环结束之后执行延迟回调.在修 ...
 - 前端 | Vue nextTick 获取更新后的 DOM
		
前两天在开发时遇到一个需求:打开对话框的时候自动聚焦其中的输入框.由于原生的 autofocus 属性不起作用,需要使用组件库提供的 focus 方法手动手动获取焦点.于是有如下代码: <el- ...
 - vue2.0 正确理解Vue.nextTick()的用途
		
什么是Vue.nextTick() 官方文档解释如下: 在下次 DOM 更新循环结束之后执行延迟回调.在修改数据之后立即使用这个方法,获取更新后的 DOM. 获取更新后的DOM,言外之意就是DOM更新 ...
 - Vue.$nextTick
		
`Vue.nextTick(callback)`,当数据发生变化,更新后执行回调. `Vue.$nextTick(callback)`,当dom发生变化,更新后执行的回调
 
随机推荐
- Python 自动化 第一周
			
1.Python简介 1.1.Python介绍 python的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏姆(中文名字:龟叔)为了在阿姆斯特丹打发时 ...
 - 丢掉DDL,我用这招3分钟清空 MySQL 9亿记录数据表
			
摘要:最近由于福建开机广告生产环境的广告日志备份表主键(int类型)达到上限(21亿多),不能再写入数据,需要重新清空下该表并将主键重置,但由于表里有8亿多记录的数据量,使用重置命令及DDL命令执行地 ...
 - Spring 环境与profile(三)——利用maven的resources、filter和profile实现不同环境使用不同配置文件
			
基本概念 profiles定义了各个环境的变量id filters中定义了变量配置文件的地址,其中地址中的环境变量就是上面profile中定义的值 resources中是定义哪些目录下的文件会被配置文 ...
 - Python/模块与包之模块
			
Python/模块与包之模块 1.什么是模块? 模块就是py文件 2.为什么要用模块? 如果在解释器上进行编码,把解释器关闭之前写的文件就不存在了,如果使用模块的话就能永久保存在磁盘中. 3.如何使用 ...
 - Python scrapy框架
			
Scrapy Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架. 其可以应用在数据挖掘,信息处理或存储历史数据等一系列的程序中.其最初是为了页面抓取 (更确切来说, 网络抓取 )所设 ...
 - JavaEE  EL & JSTL  学习笔记
			
1. EL表达式(特别重要)
 - Django:(博客系统)使用使用mysql数据&创建post/category/tag实体,并同步到数据中
			
背景: 之前也读过一些关于django的一些书,看过别人写的一些博客系统.但是总有一种看别人的都会,但自己写不出来的感觉,于是为了加深对django的学习就开始动手学习了. 环境搭建: 环境:使用py ...
 - CNN中减少网络的参数的三个思想
			
CNN中减少网络的参数的三个思想: 1) 局部连接(Local Connectivity) 2) 权值共享(Shared Weights) 3) 池化(Pooling) 局部连接 局部连接是相对于全连 ...
 - ecshop PC版本智能跳转到对应手机版页面
			
以下适用于PC跳转到ectouch手机版的写法.其他手机端的方法类似. 修改文件 includes/lib_main.php 增加以下 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ...
 - delphi 10.1 Berlin 中使用自带的 Base64 编码
			
delphi 10.1 berlin版本中,有好几个 base64 编码的单元可以使用,例如 Indy, MessageDigest_5,还有 CnBase64,我现在使用自带的 System.Net ...