I've a problem with my vuejs app (nuxt 2.15): I make my elements appear on scroll with a class .appear
that I add "manually" with this method (bind to a scroll event):
document.querySelectorAll('.part > *:not(.appear)').forEach(element => {
const posTop = rect(element).top
const trigger = window.innerHeight * 0.8
if (posTop < trigger) {
element.classList.add('appear')
}
})
This part work but the problem is that sometimes when a component re-render the class .appear
is deleted by vue. How can i fix that issue?
You're right, the re-render will clear those attributes we added via DOM API. So for most of the time we will try not to use DOM API when working with frontend frameworks like Vue.
There's this Intersection Observer API that can help us check if an element has been scrolled into the viewport or not. With this functionality, we can add a state like isSeen
in data()
, and use that state to determine what classes we should show in <template>
.
You can check this Vue SFC Playground for a live example. I would recommend you to open the Inspector and see when will the .appear
class be added to the container.
<Counter />
"show up" (well, they are already there at the very beginning, we're just adding classes on them)<Counter />
re-render, and see the .appear
class is still there
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.