What is Vue.nextTick()
The official explanation: the next DOM
execution delayed callback after the update cycle. Use this method immediately after modifying the data to get the updated one DOM
.
Note: The key point is to obtain the updated DOM. During the development process, there is a requirement that created
the node after the data update needs to be manipulated during the phase.Vue.nextTick()
the reason
When the created()
hook function is executed, DOM
no rendering is actually performed, and the DOM
operation is in vain at this time , so created
you must put Vue.nextTick()
the JS code of the DOM operation in the callback function. Corresponding to it is the mounted() hook function, because all the DOM
mounting and rendering have been completed when the hook function is executed, and DOM
there is no problem with any operation in the hook function at this time .
Case number one
<template>
<div id="app">
<div ref="msgDiv">{
{
msg1}}</div>
<br/>
<div>{
{
msg2}}</div>
<br/><br/>
<button @click="changeMsg">点击我</button>
</div>
</template>
<script>
export default {
name: 'App',
data(){
return {
msg1: "你我贷",
msg2: "理财"
}
},
methods: {
changeMsg() {
this.msg1 = "飞旋"
this.msg2 = this.$refs.msgDiv.textContent;
console.log(this.$refs.msgDiv.textContent)
this.$nextTick(function(){
console.log(this.$refs.msgDiv.textContent)
})
}
}
}
</script>
Before trigger:
After triggering:
Case 2:
<template>
<div id="app">
<div ref="msgDiv" id="msgDiv" v-if="showDiv">{
{
msg1}}</div>
<button @click="changeMsg">点击我</button>
</div>
</template>
<script>
export default {
name: 'App',
data(){
return {
msg1: "你我贷",
showDiv: false
}
},
methods: {
changeMsg() {
this.showDiv = true
console.log(document.getElementById("msgDiv"))
this.$nextTick(function(){
console.log(document.getElementById("msgDiv"))
})
}
}
}
</script>
Before
clicking: After clicking:
Note: The first console.log(document.getElementById("msgDiv"))
output after the above code is executed is null
an important concept of asynchronous update queue. Vue
When a data change is observed DOM
, it is not directly updated , but a queue is opened and all data changes that occur in the same event loop are buffered. Duplicate data will be removed during buffering, thereby avoiding unnecessary calculations and DOM
operations. Then, in the next event loop tick
, the Vue
queue is refreshed and actual work is performed.
In fact, this.showDiv = true;
it div
is still not created when it is executed , and it is not created until the next Vue
event loop. $nextTick
It is used to know when the DOM
update is completed, so the second console.log(document.getElementById("msgDiv"))
output in the above code is<div id="msgDiv">你我贷</div>