Blog>
Snippets

Using nextTick to Access Updated DOM

Show how to use Vue.js 3's nextTick function to access the updated Real DOM after changes have been made to the VDOM and the DOM has been patched.
<div id="app">
  <p ref="paragraph">{{ message }}</p>
  <button @click="updateMessage">Update Message</button>
</div>
HTML structure with a Vue instance, containing a paragraph bound to a Vue data property 'message', and a button that triggers 'updateMessage' method.
<script src="https://unpkg.com/vue@next"></script>
Include the Vue.js 3 library in the HTML.
<script>
  const { createApp, nextTick } = Vue;
  
  createApp({
    data() {
      return {
        message: 'Hello, Vue 3!'
      };
    },
    methods: {
      updateMessage() {
        this.message = 'Updated Message';
        this.$nextTick()
          .then(() => {
            const paragraphElement = this.$refs.paragraph;
            console.log(paragraphElement.textContent); // Outputs 'Updated Message'
          });
      }
    }
  }).mount('#app');
</script>
Initialize a Vue 3 application with an 'updateMessage' method that updates 'message' and uses 'nextTick' to access the updated DOM.
<style>
p {
  color: blue;
}
button {
  margin-top: 10px;
}
</style>
Simple CSS to style the paragraph text in blue and add some margin to the button.