How to listen to scroll events in vue nuxtjs?

前端 未结 2 1690
攒了一身酷
攒了一身酷 2021-02-07 10:50

I\'ve search for a solution and came up with this code

methods: {
  handleScroll () {
    console.log(window.scrollY)
  }
},
created () {
  window.addEventListen         


        
相关标签:
2条回答
  • 2021-02-07 11:28

    window is undefined because nuxt JS is server side rendered.

    So try it using process.client variable

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

    See link for more info

    0 讨论(0)
  • 2021-02-07 11:45

    Using window or any other browser-specific API in created or beforeCreate will lead to problems because platform-specific APIs like document or window are not available on the server (where SSR happens). Instead, move the logic from created into beforeMount. Leaving it in created and checking it via process.browser would work as well but is not as clean and can lead to confusion easily.

    export default {
      methods: {
        handleScroll () {
          // Your scroll handling here
          console.log(window.scrollY)
        }
      },
      beforeMount () {
        window.addEventListener('scroll', this.handleScroll);
      },
      beforeDestroy() {
        window.removeEventListener('scroll', this.handleScroll);
      }
    }
    

    Only created and beforeCreate are executed on both sides, server and client. Therefore you don't need guarding ifs in beforeMount or beforeDestroy.

    Further read about ssr-ready Vue components

    0 讨论(0)
提交回复
热议问题