摘要:这是因为在运行时出错,我们不这个错误的话,会导致整个程序崩溃掉。如果没有向中传入,并且浏览器支持的话,我们的返回的将是一个。如果不支持,就降低到用,整体逻辑就是这样。。
我们知道vue中有一个api。Vue.nextTick( [callback, context] )
他的作用是在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM。那么这个api是怎么实现的呢?你肯定也有些疑问或者好奇。下面就是我的探索,分享给大家,也欢迎大家到github上和我进行讨论哈~~
首先贴一下vue的源码,然后我们再一步步的分析
</>复制代码
/* @flow */
/* globals MessageChannel */
import { noop } from "shared/util"
import { handleError } from "./error"
import { isIOS, isNative } from "./env"
const callbacks = []
let pending = false
function flushCallbacks () {
pending = false
const copies = callbacks.slice(0)
callbacks.length = 0
for (let i = 0; i < copies.length; i++) {
copies[i]()
}
}
// Here we have async deferring wrappers using both microtasks and (macro) tasks.
// In < 2.4 we used microtasks everywhere, but there are some scenarios where
// microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. #4521, #6690) or even between bubbling of the same
// event (#6566). However, using (macro) tasks everywhere also has subtle problems
// when state is changed right before repaint (e.g. #6813, out-in transitions).
// Here we use microtask by default, but expose a way to force (macro) task when
// needed (e.g. in event handlers attached by v-on).
let microTimerFunc
let macroTimerFunc
let useMacroTask = false
// Determine (macro) task defer implementation.
// Technically setImmediate should be the ideal choice, but it"s only available
// in IE. 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)) {
macroTimerFunc = () => {
setImmediate(flushCallbacks)
}
} else if (typeof MessageChannel !== "undefined" && (
isNative(MessageChannel) ||
// PhantomJS
MessageChannel.toString() === "[object MessageChannelConstructor]"
)) {
const channel = new MessageChannel()
const port = channel.port2
channel.port1.onmessage = flushCallbacks
macroTimerFunc = () => {
port.postMessage(1)
}
} else {
/* istanbul ignore next */
macroTimerFunc = () => {
setTimeout(flushCallbacks, 0)
}
}
// Determine microtask defer implementation.
/* istanbul ignore next, $flow-disable-line */
if (typeof Promise !== "undefined" && isNative(Promise)) {
const p = Promise.resolve()
microTimerFunc = () => {
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)
}
} else {
// fallback to macro
microTimerFunc = macroTimerFunc
}
/**
* Wrap a function so that if any code inside triggers state change,
* the changes are queued using a (macro) task instead of a microtask.
*/
export function withMacroTask (fn: Function): Function {
return fn._withTask || (fn._withTask = function () {
useMacroTask = true
const res = fn.apply(null, arguments)
useMacroTask = false
return res
})
}
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
if (useMacroTask) {
macroTimerFunc()
} else {
microTimerFunc()
}
}
// $flow-disable-line
if (!cb && typeof Promise !== "undefined") {
return new Promise(resolve => {
_resolve = resolve
})
}
}
这么多代码,可能猛的一看,可能有点懵,不要紧,我们一步一步抽出枝干。首先我们看一下这个js文件里的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
if (useMacroTask) {
macroTimerFunc()
} else {
microTimerFunc()
}
}
// $flow-disable-line
if (!cb && typeof Promise !== "undefined") {
return new Promise(resolve => {
_resolve = resolve
})
}
}
我将代码精简一下。如下所示,下面的代码估计就比较容易看懂了。把cb函数放到会掉队列里去,如果支持macroTask,则利用macroTask在下一个事件循环中执行这些异步的任务,如果不支持macroTask,那就利用microTask在下一个事件循环中执行这些异步任务。
</>复制代码
export function nextTick (cb?: Function, ctx?: Object) {
callbacks.push(cb)
if (useMacroTask) {
macroTimerFunc()
} else {
microTimerFunc()
}
}
这里再次普及一下js的event loop的相关知识,js中的两个任务队列 :macrotasks、microtasks
macrotasks: script(一个js文件),setTimeout, setInterval, setImmediate, I/O, UI rendering
microtasks: process.nextTick, Promises, Object.observe, MutationObserver
执行过程:
1.js引擎从macrotask队列中取一个任务执行
2.然后将microtask队列中的所有任务依次执行完
3.再次从macrotask队列中取一个任务执行
4.然后再次将microtask队列中所有任务依次执行完
……
循环往复
那么我们再看我们精简掉的代码都是干什么的呢?我们往异步队列里放回调函数的时候,我们并不是直接放回调函数,而是包装了一个函数,在这个函数里调用cb,并且用try catch包裹了一下。这是因为cb在运行时出错,我们不try catch这个错误的话,会导致整个程序崩溃掉。 我们还精简掉了如下代码
</>复制代码
if (!cb && typeof Promise !== "undefined") {
return new Promise(resolve => {
_resolve = resolve
})
}
这段代码是干嘛的呢?也就是说我们用nextTick的时候,还可以有promise的写法。如果没有向nextTick中传入cb,并且浏览器支持Promise的话,我们的nextTick返回的将是一个Promise。所以,nextTick的写法也可以是如下这样的
</>复制代码
nextTick().then(()=>{console.log("XXXXX")})
vue源码里关于nextTick的封装的思路,也给我们一些非常有益的启示,就是我们平时在封装函数的时候,要想同时指出回调和promise的话,就可以借鉴vue中的思路。
大致的思路我们已经捋顺了。但是为什么执行macroTimerFunc或者microTimerFunc就会在下一个tick执行我们的回调队列呢?下面我们来分析一下这两个函数的定义。首先我们分析macroTimerFunc
</>复制代码
let macroTimerFunc
if (typeof setImmediate !== "undefined" && isNative(setImmediate)) {
macroTimerFunc = () => {
setImmediate(flushCallbacks)
}
} else if (typeof MessageChannel !== "undefined" && (
isNative(MessageChannel) ||
// PhantomJS
MessageChannel.toString() === "[object MessageChannelConstructor]"
)) {
const channel = new MessageChannel()
const port = channel.port2
channel.port1.onmessage = flushCallbacks
macroTimerFunc = () => {
port.postMessage(1)
}
} else {
/* istanbul ignore next */
macroTimerFunc = () => {
setTimeout(flushCallbacks, 0)
}
}
从上边的代码可以看出,如果浏览器支持setImmediate,我们就用setImmediate,如果浏览器支持MessageChannel,我们就用MessageChannel的异步特性,如果两者都不支持,我们就降价到setTimeout
,用setTimeout来把callbacks中的任务在下一个tick中执行
</>复制代码
macroTimerFunc = () => {
setTimeout(flushCallbacks, 0)
}
分析完macroTimerFunc,下面我们开始分析microTimerFunc,我把vue源码中关于microTimerFunc的定义稍微精简一下
</>复制代码
let microTimerFunc;
if (typeof Promise !== "undefined" && isNative(Promise)) {
const p = Promise.resolve()
microTimerFunc = () => {
p.then(flushCallbacks)
}
} else {
// fallback to macro
microTimerFunc = macroTimerFunc
}
从上边精简之后的代码,我们可以看到microTimerFunc的实现思路。如果支持浏览器支持promise,就用promise实现。如果不支持,就降低到用macroTimerFunc
over,整体逻辑就是这样。。看着吓人,掰开了之后好好分析一下,还是挺简单的。
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/96240.html
摘要:因为平时使用都是传回调的,所以很好奇什么情况下会为,去翻看官方文档发现起新增如果没有提供回调且在支持的环境中,则返回一个。这就对了,函数体内最后的判断很明显就是这个意思没有回调支持。 Firstly, this paper is based on Vue 2.6.8刚开始接触Vue的时候,哇nextTick好强,咋就在这里面写就是dom更新之后,当时连什么macrotask、micro...
摘要:复制代码然后在这个文件里还有一个函数叫用来把保存的回调函数给全执行并清空。其实调用的不仅是开发者,更新时,也用到了。但是问题又来了,根据浏览器的渲染机制,渲染线程是在微任务执行完成之后运行的。 当在代码中更新了数据,并希望等到对应的Dom更新之后,再执行一些逻辑。这时,我们就会用到$nextTickfuncion call...
摘要:后来尤雨溪了解到是将回调放入的队列。而且浏览器内部为了更快的响应用户,内部可能是有多个的而的的优先级可能更高,因此对于尤雨溪采用的,甚至可能已经多次执行了的,都没有执行的,也就导致了我们更新操 原发于我的博客。 前一篇文章已经详细记述了Vue的核心执行过程。相当于已经搞定了主线剧情。后续的文章都会对其中没有介绍的细节进行展开。 现在我们就来讲讲其他支线任务:nextTick和micro...
摘要:原文地址项目地址关于中使用效果,官网上的解释如下当元素插入到树或者从树中移除的时候,属性提供变换的效果,可以使用来定义变化效果,也可以使用来定义首先第一个函数是将元素插入,函数实现调用了实现代码如下写的好的代码就是文档,从注释和命名上就 src/transition 原文地址项目地址 关于 vue 中使用 transition 效果,官网上的解释如下: With Vue.js’ tra...
摘要:尽量把所有异步代码放在一个宏微任务中,减少消耗加快异步代码的执行。我们知道,如果一个异步代码就注册一个宏微任务的话,那么执行完全部异步代码肯定慢很多避免频繁地更新。中就算我们一次性修改多次数据,页面还是只会更新一次。 写文章不容易,点个赞呗兄弟专注 Vue 源码分享,文章分为白话版和 源码版,白话版助于理解工作原理,源码版助于了解内部详情,让我们一起学习吧研究基于 Vue版本 【2.5...
阅读 2693·2021-11-16 11:53
阅读 2764·2021-07-26 23:38
阅读 2089·2019-08-30 15:55
阅读 1770·2019-08-30 13:21
阅读 3699·2019-08-29 17:26
阅读 3344·2019-08-29 13:20
阅读 893·2019-08-29 12:20
阅读 3218·2019-08-26 10:21
极致性价比!云服务器续费无忧!
Tesla A100/A800、Tesla V100S等多种GPU云主机特惠2折起,不限台数,续费同价。
NVIDIA RTX 40系,高性价比推理显卡,满足AI应用场景需要。
乌兰察布+上海青浦,满足东推西训AI场景需要