Home > other >  How to use scroll to top/bottom button as globally in vue?
How to use scroll to top/bottom button as globally in vue?

Time:06-08

I made a scroll to top and scroll to bottom button. I would like to use my scroll to top and scroll to bottom as globally in my apps. This is because i have to keep copy hasScroll:false, hasVerticalScroll(){this.hasScroll=document.body.offsetHeight > window.innerHeight}; , declare <v-app v-scroll="hasVerticalScroll"> and <ScrollToTop v-if="hasScroll"/>in every pages that need this component. Is there any way to reduce the code so that i do not have to repeat all the codes in every pages to call the component?

Default.vue

<script>

export default {
    name: "DefaultLayout",
    data() {
        return {

            hasScroll: false
        };
    },
    methods: {

        hasVerticalScroll() {
          this.hasScroll = document.body.offsetHeight > window.innerHeight;
    }
  }
}
</script>

<template>
  <v-app dark v-scroll="hasVerticalScroll">

    <ScrollToTop v-if="hasScroll"/>
  </v-app>
</template>

ScrollToTop.vue

<template>
      <div v-scroll="onScroll" >
        <v-btn v-if = "!isVisible"
             fab fixed bottom right color="primary" @click="toBottom" >
            <v-icon>mdi-arrow-down-bold-box-outline</v-icon>
        </v-btn>

        <v-btn v-else
            fab fixed bottom right color="primary" @click="toTop">
            <v-icon>mdi-arrow-up-bold-box-outline</v-icon>
        </v-btn>
      </div>
</template>

<script>

export default{
    data () {
        return {
        isVisible: false,
        position: 0,
    }
  },
   methods: {
    onScroll () {
      this.isVisible = window.pageYOffset> 50
    },
    toTop () {
      this.position = window.pageYOffset
      window.scrollTo({
        top: 0,
        left: 0,
        behavior: 'smooth'
      })
    },
    toBottom(){
      let pos = this.position > 0 ? this.position : document.body.scrollHeight
      window.scrollTo({
        top: document.body.scrollHeight,
        behavior: 'smooth'
      })
    },
  }
}

</script>

CodePudding user response:

You can try to watch for route change and check for vertical scroll:

watch: {
  '$route' (to, from) {
    this.hasVerticalScroll()
  }
}

CodePudding user response:

If I understood you correctly, then you want to achieve will need to set a global event listener and listen to the event yourself and you don't need to use vuetify's v-scroll directive for that (I assume it's their directive)

Example:

        mounted() {
            this.listener = () => {
                this.isVisible = window.pageYOffset> 50
            };

            document.addEventListener('scroll', this.listener);
        },
        beforeUnmount() {
            document.removeEventListener('scroll', this.listener);
        },
  • Related