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

新手上路,请多包涵

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

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

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

错误消息是 Window is not defined

原文由 hdotluna 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.8k
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);
    }
}

查看 链接 了解更多信息

原文由 Vamsi Krishna 发布,翻译遵循 CC BY-SA 4.0 许可协议

Using window or any other browser-specific API in created or beforeCreate will lead to problems because platform-specific APIs like document or window 在服务器上不可用(发生 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 组件

原文由 manniL 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题