开发者

Vue getElementById on Mounted return undefined

When I want ge开发者_如何转开发t DOM in Vue , but I can not get.

Why use getElementById or getElementByClassName Api on Mounted Hook function return undefined?And use querySelect Api can return DOM.

Then by searching for information,I find need on Mounted use nextTick or Asynchronous operations.Doesn't Mounted Hook function mean that the DOM is mounted?

Why I can not get DOM on Mounted Hook function?

Why I need use Asynchronous operations get DOM on Mounted?


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜