1

I am having a problem while accessing the DOM using Vue3 mounted hook.

I noticed that using the getElementById or getElementByClassName methods on the mounted hook, returns undefined, and using the querySelector method returns the DOM.

After some research, I found that we should use nextTick or asynchronous operations to access the DOM in the mounted hook.

Doesn't the mounted hook itself mean the DOM is mounted?

Why do I need to use asynchronous operations or nextTick to get the DOM inside the mounted hook?

Plus: I want to know the difference of getElementById and getElementByClassName? Why I can get DOM on the mounted hook By getElementById,but I can not By getElementByClassName.

enter image description here

enter image description here

  • Direct DOM needs to be justified in Vue, it's possible that you try to do a thing that won't work correctly at all. This is very specific to your case, check https://stackoverflow.com/help/mcve before asking. – Estus Flask Dec 07 '22 at 09:38

1 Answers1

1

Use nextTick when you want to be very sure that the DOM reflects your data.

nextTick accepts a callback function that gets delayed until the next DOM update cycle. It is just the Vue way of saying, that if you ever want to execute a function after making sure that the DOM has been updated, use nextTick“.

So this is all about making sure of the DOM's presence before accessing it inside the mounted hook which is a helpful way to get rid of some unwanted output, i.e undefined.

In the below example, Vue waits to update DOM when data has been changed using the nextTick function before displaying value 3 to the browser.

mounted() {
    // Vue updates the DOM to some value 3
    this.currentTime = 3;

    // then invokes the callback, updates the DOM to 2021, and 
    // finally gives control to the browser, which displays current 
    // year.

    this.$nextTick(() => {
        let date = new Date()
        this.currentTime = date.getFullYear()
    });
}

There are a number of well-written blogs to explain nextTick and asynchronous queues operation with very good examples.

I would recommend getting through this-

  1. https://blog.logrocket.com/understanding-nexttick-in-vue-js/
  2. https://www.educative.io/answers/how-to-use-the-vuenexttick-method-in-vue
Neha Soni
  • 3,935
  • 2
  • 10
  • 32