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

Posted

技术标签:

【中文标题】如何在 vue nuxtjs 中监听滚动事件?【英文标题】:How to listen to scroll events in vue nuxtjs? 【发布时间】:2018-04-29 20:11:55 【问题描述】:

我正在寻找解决方案并想出了这段代码

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

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

错误信息是Window is not defined

【问题讨论】:

【参考方案1】:

对我来说,只使用“***”而不是“滚动”

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

【讨论】:

【参考方案2】:

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

【讨论】:

我收到一个错误:Unexpected window in created nuxt/no-globals-in-created ^来自 nuxt eslint 插件??? 请在下面查看我的答案。 现在不是process.browserprocess.client【参考方案3】:

createdbeforeCreate 中使用window 或任何其他特定于浏览器的API 会导致问题,因为特定于平台的API 如documentwindow 在服务器上不可用(发生s-s-r 的地方) .相反,将逻辑从 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 中的 if。

进一步了解s-s-r-ready Vue components

【讨论】:

很好的答案!谢谢:) 它正在为所有页面运行,我无法删除事件监听器!

以上是关于如何在 vue nuxtjs 中监听滚动事件?的主要内容,如果未能解决你的问题,请参考以下文章

vue监听指定区域的滚动,以及设置滚动值

如何在Angular项目里监听页面关闭、跳转事件?

ScrollView可以监听滚动结束事件吗

如何用js监听滚动条滚动事件?

vue子组件监听scroll事件

vue监听滚动事件 实现某元素吸顶或者固定位置显示