Handling scrolling in Vue component.

A while back I was creating an app listing job postings. This list had a "back to top" button. But I only wanted to show this button if the user has scrolled an X amount of pixels.

In the following example I will use the window.addEventListener('scroll') and Vue lifecycle hooks: mounted() and unmounted().

Both are necessary because else you keep the listeners running even if Vue has already destroyed the component.

<template>
<div class="pagination">
<button v-if="pages[1]" @click="$store.commit('loadMore')" class="load_more button primary icon-down">
<span></span>
<svg><use href="#svg_arrow"></use></svg>
</button>

<button v-if="showBackToTop" @click="backToTop" class="button secondary icon-up back_to_top" >
<span></span>
<svg><use href="#svg_arrow"></use></svg>
</button>

<ul class="f pagination" v-if="false && pages[1]">
...
</ul>
</div>
</template>

<script>
export default {
components: {},
props: [],
name: "app",
data() {
return {
showBackToTop: false,
};
},
computed: {
pages: function () {
...
},
},
watch: {},
methods: {
backToTop(key) {
console.log("key", key);
const rootElement = document.documentElement;
console.log('root', rootElement)
rootElement.scrollTo({
top: 0,
behavior: "smooth"
});
},
handleScroll(event) {
// When window is scrolled and it's beyond X amount set showBackToTop to true. Else back to falsy.
this.showBackToTop = (window.scrollY > 300);
}
},
mounted() {
window.addEventListener('scroll', this.handleScroll);
},
unmounted() {
window.removeEventListener('scroll', this.handleScroll);
},
};
</script>
<style lang="scss"></style>