I have created a scroll-to-top and scroll-to-bottom button for my application. However, I want to make these buttons accessible globally throughout the app without having to repeat the code in every page where the component is needed. Currently, I am including hasScroll:false
,
hasVerticalScroll(){this.hasScroll=document.body.offsetHeight > window.innerHeight};
, declare <v-app v-scroll="hasVerticalScroll">
, and <ScrollToTop v-if="hasScroll"/>
in each page that requires this functionality. Is there a more efficient way to simplify this process?
Default.vue
<script>
export default {
name: "DefaultLayout",
data() {
return {
hasScroll: false
};
},
methods: {
hasVerticalScroll() {
this.hasScroll = document.body.offsetHeight > window.innerHeight;
}
},
watch: {
'$route' (to, from) {
this.hasVerticalScroll()
}
}
}
</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'
})
},
}
}