摘要:而中的回调函数则会在页面渲染后才执行。还使用方法复制数组并把数组清空,这里的数组就是存放主线程执行过程中的函数所传的回调函数集合主线程可能会多次使用方法。到这里就已经实现了根据环境选择异步方法,并在异步方法中依次调用传入方法的回调函数。
Vue.nextTick的应用场景
Vue 是采用异步的方式执行 DOM 更新。只要观察到数据变化,Vue 将开启一个队列,并缓冲同一事件循环中发生的所有数据改变。然后,在下一个的事件循环中,Vue 刷新队列并执行页面渲染工作。所以修改数据后DOM并不会立刻被重新渲染,如果想在数据更新后对页面执行DOM操作,可以在数据变化之后立即使用 Vue.nextTick(callback)。
下面这一段摘自vue官方文档,关于JS 运行机制的说明:
JS 执行是单线程的,它是基于事件循环的。事件循环大致分为以下几个步骤:
(1)所有同步任务都在主线程上执行,形成一个执行栈(execution context stack)。
(2)主线程之外,还存在一个"任务队列"(task queue)。只要异步任务有了运行结果,就在"任务队列"之中放置一个事件。
(3)一旦"执行栈"中的所有同步任务执行完毕,系统就会读取"任务队列",看看里面有哪些事件。那些对应的异步任务,于是结束等待状态,进入执行栈,开始执行。
(4)主线程不断重复上面的第三步。
在主线程中执行修改数据这一同步任务,DOM的渲染事件就会被放到“任务队列”中,当“执行栈”中同步任务执行完毕,本次事件循环结束,系统才会读取并执行“任务队列”中的页面渲染事件。而Vue.nextTick中的回调函数则会在页面渲染后才执行。
例子如下:
{{test}}
// Some code...
data () {
return {
test: "begin"
};
},
// Some code...
this.test = "end";
console.log(this.$refs.test.innerText);//"begin"
this.nextTick(() => {
console.log(this.$refs.test.innerText) //"end"
})
Vue.nextTick实现原理
Vue.nextTick的源码vue项目/src/core/util/路径下的next-tick.js文件,文章最后也会贴出完整的源码
我们先来看看对于异步调用函数的实现方法:
let timerFunc
if (typeof Promise !== "undefined" && isNative(Promise)) {
const p = Promise.resolve()
timerFunc = () => {
p.then(flushCallbacks)
if (isIOS) setTimeout(noop)
}
isUsingMicroTask = true
} else if (!isIE && typeof MutationObserver !== "undefined" && (
isNative(MutationObserver) ||
MutationObserver.toString() === "[object MutationObserverConstructor]"
)) {
let counter = 1
const observer = new MutationObserver(flushCallbacks)
const textNode = document.createTextNode(String(counter))
observer.observe(textNode, {
characterData: true
})
timerFunc = () => {
counter = (counter + 1) % 2
textNode.data = String(counter)
}
isUsingMicroTask = true
} else if (typeof setImmediate !== "undefined" && isNative(setImmediate)) {
timerFunc = () => {
setImmediate(flushCallbacks)
}
} else {
timerFunc = () => {
setTimeout(flushCallbacks, 0)
}
}
这段代码首先的检测运行环境的支持情况,使用不同的异步方法。优先级依次是Promise、MutationObserver、setImmediate和setTimeout。这是根据运行效率来做优先级处理,有兴趣可以去了解一下这几种方法的差异。总的来说,Event Loop分为宏任务以及微任务,宏任务耗费的时间是大于微任务的,所以优先使用微任务。例如Promise属于微任务,而setTimeout就属于宏任务。最终timerFunc则是我们调用nextTick函数时要内部会调用的主要方法,那么flushCallbacks又是什么呢,我们在看看flushCallbacks函数:
function flushCallbacks () {
pending = false
const copies = callbacks.slice(0)
callbacks.length = 0
for (let i = 0; i < copies.length; i++) {
copies[i]()
}
}
这个函数比较简单,就是依次调用callbacks数组里面的方法。还使用slice()方法复制callbacks数组并把callbacks数组清空,这里的callbacks数组就是存放主线程执行过程中的Vue.nextTick()函数所传的回调函数集合(主线程可能会多次使用Vue.nextTick()方法)。到这里就已经实现了根据环境选择异步方法,并在异步方法中依次调用传入Vue.nextTick()方法的回调函数。nextTick函数主要就是要将callback函数存在数组callbacks中,并调用timerFunc方法:
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
timerFunc()
}
// $flow-disable-line
if (!cb && typeof Promise !== "undefined") {
return new Promise(resolve => {
_resolve = resolve
})
}
}
可以看到可以传入第二个参数作为回调函数的this。另外如果参数一的条件判断为false时则返回一个Promise对象。例如
Vue.nextTick(null, {value: "test"})
.then((data) => {
console.log(data.value) // "test"
})
这里还使用了一个优化技巧,用pending来标记异步任务是否被调用,也就是说在同一个tick内只调用一次timerFunc函数,这样就不会开启多个异步任务。
完整的源码:
import { noop } from "shared/util"
import { handleError } from "./error"
import { isIE, isIOS, isNative } from "./env"
export let isUsingMicroTask = false
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 microtasks.
// In 2.5 we used (macro) tasks (in combination with microtasks).
// However, it has subtle problems when state is changed right before repaint
// (e.g. #6813, out-in transitions).
// Also, using (macro) tasks in event handler would cause some weird behaviors
// that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109).
// So we now use microtasks everywhere, again.
// A major drawback of this tradeoff is that there are some scenarios
// where microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. #4521, #6690, which have workarounds)
// or even between bubbling of the same event (#6566).
let timerFunc
// The nextTick behavior leverages the microtask queue, which can be accessed
// via either native Promise.then or MutationObserver.
// MutationObserver has wider support, however it is seriously bugged in
// UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
// completely stops working after triggering a few times... so, if native
// Promise is available, we will use it:
/* istanbul ignore next, $flow-disable-line */
if (typeof Promise !== "undefined" && isNative(Promise)) {
const p = Promise.resolve()
timerFunc = () => {
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)
}
isUsingMicroTask = true
} else if (!isIE && typeof MutationObserver !== "undefined" && (
isNative(MutationObserver) ||
// PhantomJS and iOS 7.x
MutationObserver.toString() === "[object MutationObserverConstructor]"
)) {
// Use MutationObserver where native Promise is not available,
// e.g. PhantomJS, iOS7, Android 4.4
// (#6466 MutationObserver is unreliable in IE11)
let counter = 1
const observer = new MutationObserver(flushCallbacks)
const textNode = document.createTextNode(String(counter))
observer.observe(textNode, {
characterData: true
})
timerFunc = () => {
counter = (counter + 1) % 2
textNode.data = String(counter)
}
isUsingMicroTask = true
} else if (typeof setImmediate !== "undefined" && isNative(setImmediate)) {
// Fallback to setImmediate.
// Techinically it leverages the (macro) task queue,
// but it is still a better choice than setTimeout.
timerFunc = () => {
setImmediate(flushCallbacks)
}
} else {
// Fallback to setTimeout.
timerFunc = () => {
setTimeout(flushCallbacks, 0)
}
}
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
timerFunc()
}
// $flow-disable-line
if (!cb && typeof Promise !== "undefined") {
return new Promise(resolve => {
_resolve = resolve
})
}
}
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/110256.html
摘要:因为平时使用都是传回调的,所以很好奇什么情况下会为,去翻看官方文档发现起新增如果没有提供回调且在支持的环境中,则返回一个。这就对了,函数体内最后的判断很明显就是这个意思没有回调支持。 Firstly, this paper is based on Vue 2.6.8刚开始接触Vue的时候,哇nextTick好强,咋就在这里面写就是dom更新之后,当时连什么macrotask、micro...
摘要:这是因为在运行时出错,我们不这个错误的话,会导致整个程序崩溃掉。如果没有向中传入,并且浏览器支持的话,我们的返回的将是一个。如果不支持,就降低到用,整体逻辑就是这样。。 我们知道vue中有一个api。Vue.nextTick( [callback, context] )他的作用是在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM。那么这个...
摘要:尽量把所有异步代码放在一个宏微任务中,减少消耗加快异步代码的执行。我们知道,如果一个异步代码就注册一个宏微任务的话,那么执行完全部异步代码肯定慢很多避免频繁地更新。中就算我们一次性修改多次数据,页面还是只会更新一次。 写文章不容易,点个赞呗兄弟专注 Vue 源码分享,文章分为白话版和 源码版,白话版助于理解工作原理,源码版助于了解内部详情,让我们一起学习吧研究基于 Vue版本 【2.5...
摘要:后来尤雨溪了解到是将回调放入的队列。而且浏览器内部为了更快的响应用户,内部可能是有多个的而的的优先级可能更高,因此对于尤雨溪采用的,甚至可能已经多次执行了的,都没有执行的,也就导致了我们更新操 原发于我的博客。 前一篇文章已经详细记述了Vue的核心执行过程。相当于已经搞定了主线剧情。后续的文章都会对其中没有介绍的细节进行展开。 现在我们就来讲讲其他支线任务:nextTick和micro...
摘要:中引入了中的中引入了中的中,定义了的构造函数中的原型上挂载了方法,用来做初始化原型上挂载的属性描述符,返回原型上挂载的属性描述符返回原型上挂载与方法,用来为对象新增删除响应式属性原型上挂载方法原型上挂载事件相关的方法。 入口寻找 入口platforms/web/entry-runtime-with-compiler中import了./runtime/index导出的vue。 ./r...
阅读 1488·2021-11-24 09:38
阅读 3736·2021-11-22 15:32
阅读 3672·2019-08-30 15:54
阅读 2770·2019-08-30 15:53
阅读 1665·2019-08-30 15:52
阅读 3343·2019-08-30 13:15
阅读 2033·2019-08-29 12:21
阅读 1611·2019-08-26 18:36