Home >Web Front-end >JS Tutorial >How to implement the mounted hook function in Vue to obtain the node height
This time I will show you how to implement the mounted hook function in Vue to obtain the node height, and implement the mounted hook function in Vue to obtain the node height. What are the precautions?The following is a practical case, let’s take a look .
Problems encountered
Recently I am developing a Vue project. Several pages use a page floor sliding component, so I directly encapsulated it into a , but encountered a bug, that is, I need to get the offsetTop of this component, and then when the page scrolls to this position, set the position attribute to fixed to fix it on the screen. The problem is that when I get the offsetTop in the mounted hook function, I will get the wrong offsetTop when I open the page in a new tab, but when I refresh the current page, there will be no problem.
Positioning problem
The problem was found later, it was a loading problem. A new window opened Picture, the default is not cached, the picture is The GET request is asynchronous, and js must run faster than the image GET, so when the mounted hook function is executed, the image has not been fully loaded, and an incorrect offsetTop will be obtained.
Solution
Add the ref attribute to the image and write it in the mounted hook function in that component,
this.$refs.img.onload = ()=>{ Bus.$emit('loadImgSuccess') }
The Bus here is The EventBus used is the event response method in the two components. If you don't understand or are interested, you can click here EventBus.
In the components that need to get offsetTop
Bus.$on('loadImgSuccess', () => { var offsetTop = this.$refs.dom.offsetTop })
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Detailed explanation of using Node.js Buffer
How to build a webpack react development environment
The above is the detailed content of How to implement the mounted hook function in Vue to obtain the node height. For more information, please follow other related articles on the PHP Chinese website!