【问题标题】:IntersectionObserver doesn't work while using nuxt-link使用 nuxt-link 时 IntersectionObserver 不起作用
【发布时间】:2021-04-10 09:35:41
【问题描述】:

只要元素可见,我就使用IntersectionObserver 添加一个类,这样我就可以在我的 nuxt 项目中添加淡入/淡出动画。它运行良好,但如果我用nuxt-link 更改页面(或返回同一页面)IntersectionObserver 不会添加类(所以一切都是opacity: 0

这是我的主要 nuxt 布局 (default.vue) 中的 Intersection 观察者脚本

mounted() {

  const animate = document.querySelectorAll('.animate');

  const observer = new IntersectionObserver(entries => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        entry.target.classList.add('in')
      } else {
        entry.target.classList.remove('in')
      }
    })
  }, {
   rootMargin: '-15px',
  })

  animate.forEach(entry => {
    observer.observe(entry);
  });

},

我希望每次使用 nuxt-link 更改页面时都运行此代码

【问题讨论】:

    标签: vue.js nuxt.js nuxtjs intersection-observer


    【解决方案1】:

    我刚刚在 Nuxt 页面上实现了 IntersectionObserver,而不是布局,并且刚刚对其进行了测试 - 效果很好。

    我感觉 Nuxt 正在对组件保持活动状态且未重新安装的布局做一些事情,但由于某种原因观察者被关闭了。

    我没有对此进行测试,但我想你可以在布局中为 this.$route.name 设置一个观察者。

    当这个观察者被触发时,你可以绑定观察者。

    确保设置immediate:true,使其在第一次渲染时运行。

    类似这样的:

    computed: {
        routeName() {
            return this.$route.name;
        }
    },
    
    watch: {
      routeName: {
        immediate: true,
        handler() {
          // Bind observer here
        },
      },
    },
    

    这应该给你一个起点。您可能还需要手动处理观察者以确保没有重复。也许您可以通过某种方式检查观察者是否已设置,如果未设置,则仅初始化一个新的。

    也可以在纯粹的$route 对象本身上做一个deep 观察者。

    【讨论】:

    • 在页面而不是布局上设置 IntersectionObserver 工作得很好,非常感谢:)
    • 完美!最后甚至不必使用我的hacky解决方法!我确实想知道 Nuxt 在后台做什么,以便在路线更改时在布局中处理观察者。很高兴有帮助:)
    猜你喜欢
    • 2022-11-16
    • 1970-01-01
    • 2021-12-17
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    • 2018-07-04
    相关资源
    最近更新 更多