Batched Updates and NextTick
Illustrate how Vue.js 3 batches updates to the DOM and how to use nextTick to perform actions after the DOM has been updated.
<div id='app'>
<p>{{ message }}</p>
</div>
HTML structure with Vue data-binding. An element binds the 'message' property from the Vue instance.
<script src='https://unpkg.com/vue@next'></script>
<script>
const { createApp, nextTick } = Vue;
createApp({
data() {
return {
message: 'Hello'
};
},
mounted() {
// This will batch the updates
this.message = 'Hello World';
this.message = 'Hello Vue 3';
// Using nextTick to access the DOM after it has been updated
nextTick().then(() => {
console.log(document.querySelector('p').textContent); // 'Hello Vue 3'
});
}
}).mount('#app');
</script>
JavaScript with Vue 3 setup. It demonstrates batched updates to 'message'. The DOM will only be updated once, despite multiple changes to 'message'. The 'nextTick' function is used to log the DOM content after it's updated.
<style>
p {
color: blue;
}
</style>
CSS to style the paragraph element with blue text.