如何在Vue Nuxt.js中监听滚动事件?

24

我已经搜索了解决方案,并找到了这段代码

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

3个回答

69

createdbeforeCreate中使用window或任何其他特定于浏览器的API将会导致问题,因为像documentwindow这样的特定于平台的API在服务器上(SSR发生的地方)不可用。相反,将逻辑从created中移动到beforeMount中。把它留在created中并通过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中不需要加保护条件判断。

详细了解适用于SSR的Vue组件


1
非常好的答案!谢谢 :) - hdotluna
它正在所有页面上运行,我无法删除事件监听器! - Muzaffer Kadir Yılmaz

28

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);
    }
}

查看链接以获取更多信息。


7
我遇到了一个错误:Unexpected window in created nuxt/no-globals-in-created。意思是在created生命周期钩子函数中使用了全局变量window,这在Nuxt.js中被禁止。 - Joost Döbken
1
来自nuxt eslint插件。请看下面我的回答。 - manniL
现在使用process.client代替process.browser - Enrique Aparicio
提供的链接已失效。我认为现在应该链接到这个地方:https://v2.nuxt.com/docs/concepts/server-side-rendering/ - undefined

1
对于我来说,只能使用“wheel”而不能使用“scroll”。
 beforeMount () {
    window.addEventListener('wheel', this.handleScroll)
 },
 
  beforeDestroy() {
    window.removeEventListener('wheel', this.handleScroll);
  },

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接