App.vue
main.js
<template>
<h2>Example $nextTick() Method</h2>
<p>The $nextTick() method waits for the DOM to update so that we can get the new, updated value from the DOM after re-render.</p>
<div>
<p ref="pEl">{{ message }}</p>
<button v-on:click.once="updateMsg">Update Message</button>
<ol>
<li v-for="x in results">{{ x }}</li>
</ol>
</div>
<br>
<p>Comments to the code:</p>
<ul>
<li><span>Line 30:</span> The 'message' data property is updated. This triggers a DOM update.</li>
<li><span>Line 31:</span> The DOM update have not actually happened yet at this point, so the value we get here is the old value.</li>
<li><span>Line 32-34:</span> $nextTick() waits for the DOM to update, so at this point we get the new text value from the updated p-tag.</li>
</ul>
</template>
<script>
export default {
data() {
return {
message: '"Initial Message"',
results: []
};
},
methods: {
updateMsg() {
this.message = '"Hello! This is a new message."';
this.results.push(this.$refs.pEl.textContent);
this.$nextTick(() => {
this.results.push(this.$refs.pEl.textContent + ' (using $nextTick())');
});
}
}
};
</script>
<style scoped>
div {
border: solid black 1px;
padding: 10px;
}
span {
text-decoration: underline;
}
</style>
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
app.mount('#app')