【问题标题】:How to listen to scroll events in vue nuxtjs?如何在 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

【问题讨论】:

    标签: vue.js nuxt.js


    【解决方案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 在服务器上不可用(发生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 中的 if。

      进一步了解ssr-ready Vue components

      【讨论】:

      • 很好的答案!谢谢:)
      • 它正在为所有页面运行,我无法删除事件监听器!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-25
      • 2011-11-12
      • 1970-01-01
      • 2012-09-13
      • 1970-01-01
      • 2018-01-31
      • 2021-12-27
      相关资源
      最近更新 更多