0

I have this code and the goal from it is to update a data sticky to true if the scroll position is > than 0

export default {
  components: {
  },
  data() {
    return {
      menuVisible: false,
      sticky: false,
    }
  },
  mounted() {
    this.checkScroll()
  },
  methods: {
    checkScroll() {
      document.querySelector('body').onscroll = function() {
        console.log(window.pageYOffset > 0)
        this.sticky = window.pageYOffset > 0
      }
    },
  },
}

the problem is that even that i see the true console logged, the data is allways false ( as the initial value )

enter image description here enter image description here

Any idea why is not updating it?

Toni Michel Caubet
  • 19,333
  • 56
  • 202
  • 378

1 Answers1

3

That's because of the callback you're passing into your scroll listener. In your callback this is not the context of the vue component. I think its the body actually. You'll need to use an arrow function or pass the vue instance into the callback as an argument. Arrow function is easiest. An arrow function retains the context where it was defined rather than inheriting the context of the object that calls it. Here is a good post/answer about the difference between normal and arrow functions.

document.querySelector('body').onscroll = () => {
    console.log(window.pageYOffset > 0)
    this.sticky = window.pageYOffset > 0
}
Craig Harshbarger
  • 1,863
  • 3
  • 18
  • 29