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.

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

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

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

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)
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);
<style lang="scss"></style>