scrollTop using computed in vue.js

Issue

Here is part of my code

<template>
  <button v-show="visible" @click="backToTop">👆</button>
</template>

<script lang="ts">
export default {
  computed: {
    visible() {
      return document.documentElement.scrollTop != 0
    }
  }
}
</script>

The button doesn’t disappear when i scroll the page to the top.

Solution

You need to listen to scroll event, try like following snippet:

const app = Vue.createApp({
  data() {
    return {
      visible: false
    }
  },
  methods: {
    handleScroll (event){
      this.visible = window.scrollY != 0 ? true : false
    },
    backToTop() {
      window.scrollTo({
        top: 0,
        left: 0,
        behavior: 'smooth'
      })
    }
  },
  created () {
    window.addEventListener('scroll', this.handleScroll);
  },
  destroyed () {
    window.removeEventListener('scroll', this.handleScroll);
  },
})
app.mount('#demo')
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" integrity="sha512-wnea99uKIC3TJF7v4eKk4Y+lMz2Mklv18+r4na2Gn1abDRPPOeef95xTzdwGD9e6zXJBteMIhZ1+68QC5byJZw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <p>x</p><p>x</p><p>x</p><p>x</p>
  <button v-show="visible" @click="backToTop">👆</button>
  <p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p>
</div>

Answered By – Nikola Pavicevic

Answer Checked By – Dawn Plyler (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.