我在使用Vue3挂载钩子访问DOM时遇到问题。
我注意到在挂载的钩子上使用getElementById
或getElementByClassName
方法返回未定义,而使用querySelector
方法返回DOM。
经过一番研究,我发现我们应该使用nextTick
或asynchronous operations
来访问挂载钩子中的DOM。
挂载的钩子本身不意味着DOM被挂载了吗?
为什么我需要使用asynchronous operations
或nextTick
来获得挂载钩子内的DOM ?
加上:我想知道getElementById
和getElementByClassName
有什么区别?为什么我可以通过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和异步队列操作。
我建议你完成这个-
- https://blog.logrocket.com/understanding-nexttick-in-vue-js/
- https://www.educative.io/answers/how-to-use-the-vuenexttick-method-in-vue