$nextTick调用时机以及作用
当数据更新并在dom中渲染后,会自动调用执行,简单来说就是获取更新之后的dom
由于vue响应式不是数据改变dom立即改变,所以未使用$nextTick之前立即去获取dom数据,得到的是改变之前的数据
示例
<template>
<div>
<div @click='changeMsg' ref="btnone">{{msg1}}</div>
<div @click='changeMsg' ref="btntwo">{{msg2}}</div>
</div>
</template>
<script>
export default{
data(){
return{
msg1:'hello',
msg2:'hello word'
}
},
methods:{
changeMsg(){
this.msg1 = 'hello1'
this.msg2 = 'hello1 word'
console.log(this.$refs.btnone.innerText); // hello
this.$nextTick(()=>{
console.log(this.$refs.btntwo.innerText); // hello1 word
})
}
}
}
</script>
应用场景
在vue生命周期create()函数中进行dom操作
原因:在create()函数执行的时候,dom没有渲染,这个时候进行dom操作会报错,所以一定要将操作dom的动作也就是js代码放在$nextTick的回调函数中
<template>
<div>
<div @click='changeMsg' ref="btnone">{{msg1}}</div>
<div @click='changeMsg' ref="btntwo">{{msg2}}</div>
</div>
</template>
<script>
export default{
data(){
return{
msg1:'hello',
msg2:'hello word'
}
},
created(){
console.log(this.$refs.btnone.innerText); // 报错 Error in created hook: "TypeError: Cannot read properties of undefined (reading 'innerText')
this.$nextTick(()=>{
console.log(this.$refs.btntwo.innerText); // hello word
})
}
}
</script>
在数据变化后立即执行的某个操作,而这个操作需要用到随数据改变而改变的dom结构
原因:vue异步执行dom更新,只要观察到数据变化,vue将开启一个队列,并缓存在同一事件中的所有数据改变,如果同一个watch被多次触发,只会记录最后一次。然后再下一个事件循环中,vue刷新队列并执行已去重的工作,vue 在内部尝试对异步队列使用原生的 promise.then和MessageChannel,如果执行环境不支持,会采用 setTimeout代替。
例如,当你设置vm.data = 'new value',该组件不会立即重新渲染。当刷新队列时,组件会在事件循环队列清空时的下一个“tick”更新。为了在数据变化之后等待 Vue 完成更新 DOM ,可以在数据变化之后立即使用Vue.nextTick(callback) 。这样回调函数在 DOM 更新完成后就会调用。
<template>
<div>
<h1 ref="hbox" style="white-space: pre-wrap;">{{hmsg}}</h1>
<button @click='changeMsg'>点击加一行</button>
</div>
</template>
<script>
import {
nextTick
} from "vue";
export default {
data() {
return {
hmsg: '',
}
},
methods: {
changeMsg() {
this.hmsg += '我是标题\n'
console.log(this.$refs.hbox.offsetHeight); // 0
this.$nextTick(()=>{
console.log(this.$refs.hbox.offsetHeight); // 42
})
}
}
}
</script>
nextTick源码浅析
使用方法
nextTick用于延迟执行一段代码,接收两个参数:回调函数和执行回调函数的上下文环境,如果没有提供回调函数,将返回一个promise对象
源码
/**
* Defer a task to execute it asynchronously.
*/
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]()
}
}
// 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 if */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
var p = Promise.resolve()
var logError = err => { console.error(err) }
timerFunc = () => {
p.then(nextTickHandler).catch(logError)
// 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 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
var counter = 1
var observer = new MutationObserver(nextTickHandler)
var textNode = document.createTextNode(String(counter))
observer.observe(textNode, {
characterData: true
})
timerFunc = () => {
counter = (counter + 1) % 2
textNode.data = String(counter)
}
} else {
// fallback to setTimeout
/* istanbul ignore next */
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()
}
if (!cb && typeof Promise !== 'undefined') {
return new Promise((resolve, reject) => {
_resolve = resolve
})
}
}
})()
粗浅解析
三个变量
callbacks:存储所有需要执行的回调函数
pending:判断是否有正在执行的回调函数
timerFunc:触发执行回调函数
nextTickHandler函数
用来执行callbacks里存储的所有回调函数,并将触发方式赋值给timerFunc
timerFunc函数
判断是否支持promise,如果支持则利用promise来执行回调函数;
如果支持MutationObserver,则实例化一个观察者对象,文本节点发生变化时,执行回调函数。
如果都不支持,则利用setTimeout并且设置延时为0。
queueNextTick函数
因为nextTick是一个即时函数,所以用queueNextTick函数接受用户传入的参数,然后往callbacks里存入回调函数。