访问DOM使用getElementById返回未定义的Vue挂载钩子



我在使用Vue3挂载钩子访问DOM时遇到问题。

我注意到在挂载的钩子上使用getElementByIdgetElementByClassName方法返回未定义,而使用querySelector方法返回DOM。

经过一番研究,我发现我们应该使用nextTickasynchronous operations来访问挂载钩子中的DOM。

挂载的钩子本身不意味着DOM被挂载了吗?

为什么我需要使用asynchronous operationsnextTick来获得挂载钩子内的DOM ?

加上:我想知道getElementByIdgetElementByClassName有什么区别?为什么我可以通过getElementById在挂载的钩子上获得DOM,但我不能通过getElementByClassName.

输入图片描述

输入图片描述

当您希望非常确定DOM反映您的数据时,请使用nextTick。

nextTick接受一个延迟到下一个回调函数DOM更新周期。这只是一种说法,如果你曾经我希望在确保DOM已经存在之后执行一个函数

所以这一切都是为了确保DOM的存在,然后在挂载的钩子中访问它,这是一个有用的方法来摆脱一些不想要的输出,即未定义。

在下面的例子中,当使用nextTick函数更改数据时,在向浏览器显示值3之前,Vue等待更新DOM。

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()
});
}

有许多写得很好的博客用很好的例子来解释nextTick和异步队列操作。

我建议你完成这个-

  1. https://blog.logrocket.com/understanding-nexttick-in-vue-js/
  2. https://www.educative.io/answers/how-to-use-the-vuenexttick-method-in-vue

最新更新