How to automatically scroll to top in Nuxt/Vue when clicked on the button?

1.2k Views Asked by At

I'm trying to set scrolling to top when user clicks on the button but i get two problems. First of them is buttons is not displayed on the screen. Secondly, button for scrolling to top doesn't work. Here is my scrollToTop Component:

<template>
  <div>
    <button v-if="showButton" @click="scrollToTop" class="scroll-to-top-btn">Top</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      showButton: false,
    }
  },
  methods: {
    scrollToTop() {
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      })
    },
    handleScroll() {
      if (window.pageYOffset > 100) {
        this.showButton = true;
      } else {
        this.showButton = false;
      }
    },
  },
  beforeMount() {
    window.addEventListener('scroll', this.handleScroll);
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll);
  },
}
</script>

<style>
.scroll-to-top-btn {
  position: fixed;
  bottom: 20px;
  right: 20px;
  padding: 10px;
  border-radius: 50%;
  background-color: #0077cc;
  color: white;
  font-size: 16px;
  cursor: pointer;
}
</style>
0

There are 0 best solutions below