Vue nextTick 机制
背景
我们先来看一段Vue的执行代码:
export default {data () {return {msg: 0}},mounted () {this.msg = 1this.msg = 2this.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.idif (has[id] == null) {has[id] = trueif (!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 - 1while (i > index && queue[i].id > watcher.id) {i--}queue.splice(i + 1, 0, watcher)}// queue the flushif (!waiting) {waiting = truenextTick(flushSchedulerQueue)}}
}
这里面的nextTick(flushSchedulerQueue)
中的flushSchedulerQueue
函数其实就是watcher
的视图更新:
function flushSchedulerQueue () {flushing = truelet watcher, id...for (index = 0; index < queue.length; index++) {watcher = queue[index]id = watcher.idhas[id] = nullwatcher.run()...}
}
另外,关于waiting
变量,这是很重要的一个标志位,它保证flushSchedulerQueue
回调只允许被置入callbacks
一次。
接下来我们来看看nextTick
函数,在说nexTick
之前,需要你对Event Loop
、microTask
、macroTask
有一定的了解,Vue nextTick 也是主要用到了这些基础原理。如果你还不了解,可以参考我的这篇文章Event Loop 简介
好了,下面我们来看一下他的实现:
export const nextTick = (function () {const callbacks = []let pending = falselet timerFuncfunction nextTickHandler () {pending = falseconst copies = callbacks.slice(0)callbacks.length = 0for (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) ||// PhantomJSMessageChannel.toString() === '[object MessageChannelConstructor]')) {const channel = new MessageChannel()const port = channel.port2channel.port1.onmessage = nextTickHandlertimerFunc = () => {port.postMessage(1)}} else/* istanbul ignore next */if (typeof Promise !== 'undefined' && isNative(Promise)) {// use microtask in non-DOM environments, e.g. Weexconst p = Promise.resolve()timerFunc = () => {p.then(nextTickHandler)}} else {// fallback to setTimeouttimerFunc = () => {setTimeout(nextTickHandler, 0)}}return function queueNextTick (cb?: Function, ctx?: Object) {let _resolvecallbacks.push(() => {if (cb) {try {cb.call(ctx)} catch (e) {handleError(e, ctx, 'nextTick')}} else if (_resolve) {_resolve(ctx)}})if (!pending) {pending = truetimerFunc()}// $flow-disable-lineif (!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) ||// PhantomJSMessageChannel.toString() === '[object MessageChannelConstructor]')) {const channel = new MessageChannel()const port = channel.port2channel.port1.onmessage = nextTickHandlertimerFunc = () => {port.postMessage(1)}} else/* istanbul ignore next */if (typeof Promise !== 'undefined' && isNative(Promise)) {// use microtask in non-DOM environments, e.g. Weexconst p = Promise.resolve()timerFunc = () => {p.then(nextTickHandler)}} else {// fallback to setTimeouttimerFunc = () => {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(() => { // macroTaskconsole.log('3')}, 0)Promise.resolve().then(function () { //microTaskconsole.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.js 升级踩坑小记
【Vue源码】Vue中DOM的异步更新策略以及nextTick机制
转载于:https://www.cnblogs.com/tiedaweishao/p/8967127.html
Vue nextTick 机制相关推荐
- 浏览器事件循环机制与Vue nextTick的实现
浏览器事件循环机制 先上一段简单的代码 console.log('aa'); setTimeout(() => { console.log('bb')}, 0); Promise.resolve ...
- 清空div中的内容而不刷新整个页面_Vue中的$nextTick机制
nextTick 出现的前提 因为Vue是异步驱动视图更新数据的,即当我们在事件中修改数据时,视图并不会即时的更新,而是等在同一事件循环的所有数据变化完成后,再进行视图更新.类似于Event Loop ...
- Vue源码阅读一:说说vue.nextTick实现
用法: 在下次 DOM 更新循环结束之后执行延迟回调.在修改数据之后立即使用这个方法,获取更新后的 DOM. 疑惑: 怎么实现的延迟回调 原理: JavaScript语言的一大特点就是单线程,同一个时 ...
- Vue.nextTick()理解
什么是Vue.nextTick() 官方解释:在下次 DOM 更新循环结束之后执行延迟回调.在修改数据之后立即使用这个方法,获取更新后的 DOM. 注意:重点是获取更新后的DOM 就是在开发过程中有个 ...
- Vue.nextTick和Vue.$nextTick
`Vue.nextTick(callback)`,当数据发生变化,更新后执行回调. `Vue.$nextTick(callback)`,当dom发生变化,更新后执行的回调. 参考原文:http:// ...
- vue.$nextTick 解决了哪些问题
vue.$nextTick 解决了哪些问题 转载于:https://www.cnblogs.com/ivan5277/p/10817451.html
- [vue] $nextTick有什么作用?
[vue] $nextTick有什么作用? 处理数据动态变化后,dom还未及时更新的问题.nexttick就可以获取到数据更新后最新的dom变化 个人简介 我是歌谣,欢迎和大家一起交流前后端知识.放弃 ...
- 什么是Vue.nextTick()
什么时候需要用的Vue.nextTick() 你在Vue生命周期的created()钩子函数进行的DOM操作一定要放在Vue.nextTick()的回调函数中.原因是什么呢,原因是在created() ...
- vue.nextTick()方法的使用详解(简单明了)
什么是Vue.nextTick()?? 定义:在下次 DOM 更新循环结束之后执行延迟回调.在修改数据之后立即使用这个方法,获取更新后的 DOM. 所以就衍生出了这个获取更新后的DOM的Vue方法.所 ...
最新文章
- [Java并发编程实战] 共享对象之可见性
- 实现canvas连线
- python实现函数ifodd_09-Python笔记整理(函数)
- ORACLE 表空间SQL
- MAX10 ADC的一些基知识
- 神盾解密工具 之 解密 “ PHP 神盾解密工具 ”
- 电脑计算器_教训!19年中级败给了电脑计算器,CPA难道要步后尘?
- SparkSQL默认存储格式入门
- 如何在使用 Spotify 时更好地保护您的隐私?
- 批量删除2012年9月份以前的表
- 解决 Windows XP 桌面图标阴影的情况
- 表示自己从头开始的句子_表示一切从头开始的唯美句子38条
- Gradle 2.0 用户指南翻译——第十九章. Gradle 守护进程
- 在网页上播放本地视频
- 进制转换(任意进制转换)
- win10无法访问xp计算机,XP系统访问Win10打印机被拒绝的解决方法
- 我国电子商务五大发展阶段
- 腾讯云、阿里云和百度云的优劣势各是什么?
- 深圳大学算法设计实验五
- 微信公众平台初级使用教程
热门文章
- java 内存泄漏 工具_Java剖析工具JProfiler入门使用教程:查找内存泄漏的方法
- java正则匹配英文句号_「正则表达式」王国奇遇记
- JAVA16版本.JDK16关于TCP和UDP的优化
- 三篇论文之bigtable
- php mysql 大量读取_PHP使用PDO从mysql读取大量数据处理详解
- 《数据库SQL实战》获取当前(to_date='9999-01-01')薪水第二多的员工的emp_no以及其对应的薪水salary
- 《剑指offer》求二叉树的最小深度(非递归法)
- python3扫盲系列-(3)
- javascript的全局变量
- Java堆外内存:堆外内存溢出问题排查