I am trying to listen to scroll event in vue component, but when I have tried to set it up like this:
<div id="app"
:class="{'show-backdrop': isLoading || showBackdrop}"
@scroll="handleScroll">
And then in the methods:
handleScroll () {
const header = document.querySelector('#header');
const content = document.querySelector('#content');
const rect = header.getBoundingClientRect();
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
const headerTop = rect.top + scrollTop;
if (rect.top <= 0) {
header.classList.add('fixed');
content.classList.add('content-margin');
} else {
header.classList.remove('fixed');
content.classList.remove('content-margin');
}
}
That is not working. I had to do a workaround like this:
beforeMount () {
window.addEventListener('scroll', this.handleScroll);
},
beforeDestroy () {
window.removeEventListener('scroll', this.handleScroll);
}
Why is the first approach not working, that should be the Vue way of doing things?