如何在vue nuxtjs中监听滚动事件?

How to listen to scroll events in vue nuxtjs?

我搜索了一个解决方案并想出了这个代码

methods: {
  handleScroll () {
    console.log(window.scrollY)
  }
},
created () {
  window.addEventListener('scroll', this.handleScroll);
},
destroyed () {
  window.removeEventListener('scroll', this.handleScroll);
}

不幸的是,这对我不起作用。我还尝试将 window 更改为 document.body。

错误信息是Window is not defined

window 未定义,因为 nuxt JS 是服务器端呈现的。

所以尝试使用 process.client 变量

methods: {
  handleScroll () {
    console.log(window.scrollY)
  }
},
created () {
    if (process.client) { 
        window.addEventListener('scroll', this.handleScroll);
    }
},
destroyed () {
    if (process.client) { 
        window.removeEventListener('scroll', this.handleScroll);
    }
}

有关详细信息,请参阅 link

createdbeforeCreate 中使用 window 或任何其他特定于浏览器的 API 会导致问题,因为特定于平台的 API 如 documentwindow 在服务器(发生 SSR 的地方)上不可用。相反,将逻辑从 created 移动到 beforeMount。将其保留在创建状态并通过 process.browser 检查它也可以,但不那么干净并且容易导致混淆。

export default {
  methods: {
    handleScroll () {
      // Your scroll handling here
      console.log(window.scrollY)
    }
  },
  beforeMount () {
    window.addEventListener('scroll', this.handleScroll);
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll);
  }
}

只有createdbeforeCreate在服务器端和客户端都执行。因此,您不需要在 beforeMountbeforeDestroy.

中保护 ifs

进一步阅读 ssr-ready Vue components

我只使用 'wheel' 而不是 'scroll'

 beforeMount () {
    window.addEventListener('wheel', this.handleScroll)
 },
 
  beforeDestroy() {
    window.removeEventListener('wheel', this.handleScroll);
  },