Vue.nextTick( [callback, context] )
- 参数:
{Function} [callback]
{Object} [context] - 用法:
在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM。
使用场景
- 在created里想要操纵dom时,因为在created的时候dom还没有渲染完成,直接操作dom是拿不到的,需要在nextTick获取。 在
mounted()
中进行任何DOM操作都不会有问题, 因为在mounted()
执行时所有的DOM挂载和渲染都已完成
<div ref='myRef'>value</div>
* * *
created () {
// 直接获取会报错,因为拿不到dom:"TypeError: Cannot set property 'innerText' of undefined"
console.log(this.$refs.myRef) // undefined
this.$refs.myRef.innerText = "设值" //报错
}
所以在created钩子中进行的DOM操作,不使用$nextTick()会报错:
// 正确使用方式
created () {
this.$nextTick(() => {
this.$refs.myRef.innerText = "设值"
})
}
- 在使用第三方插件时 ,这些插件需要dom动态变化后应用,这时候就需要使用$nextTick()来重新应用插件的方法,比如使用swiper
this.nextTick(function(){
var swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
autoplay: 2500
})
})
源码解析
Vue.nextTick中的回调函数会在页面渲染后才执行,因此会需要用到异步调用。
这里的异步主要使用了宏任务和微任务(可以看我这篇文章)
下面这段代码判断了当前运行环境支持的异步方法,优先级依次是Promise、MutationObserver、setImmediate和setTimeout,如果有兴趣可以去了解一下,简单的理解就是timerFunc就是一个异步执行函数
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) ||
// 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)
}
}
上面代码里我们看到timerFunc这个异步函数里面执行的是flushCallbacks,这个函数的作用就是依次执行了callbacks数组中的方法,callbacks数组放着所有调用Vue.nextTick传过来的callback。
const callbacks = []
function flushCallbacks () {
pending = false
const copies = callbacks.slice(0)
callbacks.length = 0
for (let i = 0; i < copies.length; i++) {
copies[i]()
}
}
最后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
})
}
}
总结
根据当前执行环境使用异步方法
- Promise
- MutationObserver
- setImmediate
- setTimeout
在下次 DOM 更新循环结束之后执行延迟回调
完整源码
Vue.nextTick源码路径/node_modules/vue/src/core/util/next-tick.js
/* @flow */
/* globals MutationObserver */
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]()
}
}
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) ||
// 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
})
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。