The result is undefined when getting the children of the HTMLCollection list in Vue
mounted()
When trying to get through document.querySelectorAll()
the hook function of Vue, HTMLCollection
it is found that the returned result is undefined, and the value of length is also 0:
According to the query on Vue's official website, the mounted hook function cannot guarantee that all subcomponents are mounted:
Called after the instance is mounted, the element passed to app.mount has been replaced by the newly created vm.$el. If the root instance is mounted on an element within the document, vm.$el will also be within the document when mounted is called. Note that mounted does not guarantee that all subcomponents are also mounted. If you want to wait for the entire view to be rendered, you can use vm.$nextTick inside mounted:
But after I added $nextTick
the instance method, it is still the same phenomenon, which is confusing.
So I thought of MutationObserver
monitoring the changes of the DOM by using , and get it after all the DOM has been rendered. code show as below:
async mounted() {
// 监视DOM,全部DOM加载完毕后再调用回调函数
this.observer = new MutationObserver(this.getDir);
this.observer.observe(document.querySelector(`#content`), {
childList: true,
subtree: true,
attributes: true
});
}
The result is successful:
about MutationObserver
moving to MDN or other blog posts.
Of course there must be other better methods, this method is for reference only.