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

dev*_*una 4 vue.js nuxt.js

我正在寻找解决方案并提出了这个代码

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

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

错误消息是 Window is not defined

Vam*_*hna 12

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

所以尝试使用process.browser变量

methods: {
  handleScroll () {
    console.log(window.scrollY)
  }
},
created () {
    if (process.browser) { 
        window.addEventListener('scroll', this.handleScroll);
    }
},
destroyed () {
    if (process.browser) { 
        window.removeEventListener('scroll', this.handleScroll);
    }
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅链接

  • 我收到一个错误:“在创建的nuxt / no-globals-in-created中出现了意外的窗口” (4认同)

man*_*niL 7

windowcreated或中使用或任何其他特定于浏览器的API beforeCreate会导致问题,因为平台特定的API(例如发生SSR的服务器)在服务器上不可用documentwindow不可用。而是将逻辑从创建移动到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);
  }
}
Run Code Online (Sandbox Code Playgroud)

只有createdbeforeCreate在服务器和客户端双方上执行。因此,您无需在beforeMount或中监视ifs beforeDestroy

进一步阅读有关支持SSR的Vue组件