首先,我们可以参考一下官网的解释 :
将回调推迟到下一个 DOM 更新周期之后执行。在更改了一些数据以等待 DOM 更新后立即使用它。
说了一堆,怎么解释这句话,我觉得上代码是最好解释的
<template>
<div id="app">
<h1 ref="hello">{{value}}</h1>
</div>
</template>
<script>
export default {
name: "hello",
data() {
return {
value: "hello vue.js",
};
},
created(){
console.log("created函数nextTick外",this.$refs['hello']);
this.$nextTick(()=>{
console.log("created函数nextTick内",this.$refs['hello']);
})
},
mounted(){
console.log("mounted函数nextTick外",this.$refs['hello']);
this.$nextTick(()=>{
console.log("mounted函数nextTick内",this.$refs['hello']);
})
}
}
</script>
看看运行结果:
我们会发现created()钩子函数中并没有进行任何的渲染,nextTick回调中的数据是等DOM渲染之后才进行调用。这样是不是就可以理解官网给的解释呢?将回调推迟到下一个DOM更新周期之后执行,如果还没有我们再看另外一个例子
<template>
<div id="app">
<h1 ref="hello">{{value}}</h1>
<button @click="change">chang</button>
</div>
</template>
<script>
export default {
name: "hello",
data() {
return {
value: "hello vue.js",
};
},
methods: {
change() {
this.value = "hello world";
console.log("change方法nextTick外:",this.$refs['hello'].innerHTML);
this.$nextTick(()=>{
this.value = "hello world";
console.log("change方法nextTick内",this.$refs['hello'].innerHTML);
})
}
}
</script>
当我们点击上面的change按钮,输出结果如下
我们会发现,在change方法nextTick外部修改了value的值,视图已经更新,但是DOM还未更新,打印的还是之前的数据:hello vue.js 而在change方法nextTick函数内部回调中是DOM更新之后的数据: hello world。 nextTick回调中得到了DOM更新后的数据。
应用场景:
场景一:Vue生命周期created钩子函数中想要进行DOM操作,必须放在Vue.nextTick()回调函数中。因为created()钩子函数在执行的时候DOM其实还未进行任何渲染,而此时进行DOM操作时完全没有任何用。(上面的例子一)
场景二:在数据变化后想要执行某个操作,而这个操作需要DOM更新后才能得到的时候,需要将这个操作放进Vue.nextTick()回调函数中(上面的实例二)