How to listen to scroll events in vue nuxtjs?

前端 未结 2 1689
攒了一身酷
攒了一身酷 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

提交回复
热议问题