简体   繁体   English

如何使用 vue 使元素出现在滚动条上

[英]How to make element appear on scroll with vue

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):我的 vuejs 应用程序(nuxt 2.15)有问题:我使用.appear使我的元素出现在滚动上。出现我用这种方法“手动”添加的(绑定到滚动事件):

 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.这部分工作,但问题是有时当一个组件重新渲染 class .appear被 vue 删除。 How can i fix that issue?我该如何解决这个问题?

You're right, the re-render will clear those attributes we added via DOM API.没错,重新渲染会清除我们通过 DOM API 添加的那些属性。 So for most of the time we will try not to use DOM API when working with frontend frameworks like Vue.因此,在大多数情况下,在使用 Vue 等前端框架时,我们会尽量不使用 DOM API。

There's this Intersection Observer API that can help us check if an element has been scrolled into the viewport or not.这个Intersection Observer API可以帮助我们检查元素是否已滚动到视口中。 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> .有了这个功能,我们可以在data()中添加一个像 isSeen 一样的isSeen ,并使用该 state 来确定我们应该在<template>中显示哪些类。

You can check this Vue SFC Playground for a live example.您可以查看此Vue SFC Playground以获取实时示例。 I would recommend you to open the Inspector and see when will the .appear class be added to the container.我建议您打开 Inspector 并查看何时将.appear class 添加到容器中。

  • Scroll down to see those <Counter /> "show up" (well, they are already there at the very beginning, we're just adding classes on them)向下滚动以查看那些<Counter /> “出现”(嗯,它们在一开始就已经存在,我们只是在它们上添加类)
  • Click "Increment" to make <Counter /> re-render, and see the .appear class is still there点击“增量”使<Counter />重新渲染,看到.appear class 还在

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM