Vue cannot obtain the id attribute because getElementById is used in the "created()" hook function, and Vue has not yet completed mounting; the solution is to change "created() {let serachBox = document. getElementById('searchBox');...}" code can be migrated to the "mounted()" hook function.
The operating environment of this tutorial: Windows 10 system, vue3 version, DELL G3 computer
What should I do if vue cannot obtain the id attribute?
The result of using getElementById in Vue is that the returned element is null?
When I get this requirement, my first idea is to get the size of the fixed element through element.getBoundingClientRect
, and then get the size of the fixed element through document.body.offsetHeight
The height of the view area, and finally the size of the main area is dynamically calculated.
After confirming the idea, I started coding, so I wrote the following code in created:
//此处省去无关代码 created() { let serachBox = document.getElementById('searchBox'); let searchRect = serachBox .getBoundingClientRect(); console.log('rect',searchRect ); let dffsetHeight = document.body.offsetHeight; this.tHeight = ( dffsetHeight - searchRect .bottom - 100 );},
As a result, the console reported an error directly. The error was as follows:
According to the error description, I printed the searchBox
element upwards. At this time, the console printed the result as null.
, this is a bit interesting.
Looking carefully, it turns out that I used getElementById
in the created() hook function. At this time Vue has not completed mounting, so it cannot obtain the Dom element through getElementById
, so the console prints null
. After finding the reason, I migrated the above code to the mounted()
hook function, and the console printed the correct result.
Although the problem was found, the rendering result of the page could not meet my needs. We have to continue to find a way.
Finally created() is combined with this.$nextTick() to achieve business requirements The final code is as follows:
created() { this.$nextTick(function () { let serachBox = document.getElementById('searchBox'); let searchRect = serachBox .getBoundingClientRect(); console.log('rect',searchRect ); let dffsetHeight = document.body.offsetHeight; this.tHeight = ( dffsetHeight - searchRect .bottom - 100 ); })},
This bug is mainly caused by two aspects.
First, I habitually handle business logic in the created hook function
The second reason is that I am not familiar enough with the life cycle of Vue, and I made a mistake. confused.
Recommended learning: "vue video tutorial"
The above is the detailed content of What should I do if vue cannot get the id attribute?. For more information, please follow other related articles on the PHP Chinese website!