Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen to scroll events in vue nuxtjs?

Tags:

vue.js

nuxt.js

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

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

Unfortunately, this doesn't work for me. I also tried to change window to document.body.

The error message was Window is not defined

like image 462
hdotluna Avatar asked Nov 16 '17 10:11

hdotluna


People also ask

How to listen scroll event in Vuejs?

addEventListener method to listen to the scroll event on the browser window. We call window. addEventListener with 'scroll' in the created hook to add the handleScroll scroll event listener when the component is mounted. And in the destroyed hook, we call window.


2 Answers

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

like image 164
manniL Avatar answered Oct 19 '22 05:10

manniL


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

like image 24
Vamsi Krishna Avatar answered Oct 19 '22 06:10

Vamsi Krishna