Blog>
Snippets

Usage of Vue.nextTick to Manipulate DOM After VDOM Updates

Provide an example of how to use Vue.nextTick to manipulate the real DOM after the Virtual DOM has been updated.
<div id="app">
  <button @click="updateMessage">Change Message</button>
  <p ref="myParagraph">{{ message }}</p>
</div>
HTML content with a Vue instance mounted to the div with id 'app'. It has a button that triggers the 'updateMessage' method and a paragraph that displays the 'message' data property. A Vue reference named 'myParagraph' is assigned to the paragraph element for direct DOM access.
new Vue({
  el: '#app',
  data: {
    message: 'Original message'
  },
  methods: {
    updateMessage() {
      // Update the message in the Vue instance's data
      this.message = 'Updated message';
      
      // Use Vue.nextTick to manipulate the DOM after the VDOM has been updated
      this.$nextTick(() => {
        // Access the real DOM element using the reference
        this.$refs.myParagraph.style.color = 'red';
      });
    }
  }
});
JavaScript code defining a Vue instance. The 'updateMessage' method updates the message and uses 'Vue.nextTick' to manipulate the real DOM only after the associated VDOM has been updated, ensuring consistency between the virtual and real DOM.
<style>
#app button {
  margin-bottom: 10px;
}
</style>
CSS to style the button within the #app div, providing a bottom margin.