Created
May 22, 2021 05:30
-
-
Save ShuJun-Junical/db9021be035456b0c8f6c12631f5fc8e to your computer and use it in GitHub Desktop.
Vue 组件:一键回顶按钮
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<v-fab-transition> | |
<v-btn | |
v-show="btnFlag" | |
color="pink" | |
dark | |
bottom | |
right | |
fab | |
fixed | |
@click="backTop" | |
> | |
<v-icon>mdi-arrow-up-thick</v-icon> | |
</v-btn> | |
</v-fab-transition> | |
</template> | |
<script> | |
export default { | |
name: 'BackTop', | |
data() { | |
return { | |
btnFlag: false, | |
}; | |
}, | |
mounted() { | |
window.addEventListener('scroll', this.scrollToTop); | |
}, | |
destroyed() { | |
window.removeEventListener('scroll', this.scrollToTop); | |
}, | |
methods: { | |
backTop() { | |
const that = this; | |
const timer = setInterval(() => { | |
const ispeed = Math.floor(-that.scrollTop / 5); | |
document.documentElement.scrollTop = document.body.scrollTop = | |
that.scrollTop + ispeed; | |
if (that.scrollTop === 0) { | |
clearInterval(timer); | |
} | |
}, 16); | |
}, | |
scrollToTop() { | |
const that = this; | |
const scrollTop = | |
window.pageYOffset || | |
document.documentElement.scrollTop || | |
document.body.scrollTop; | |
that.scrollTop = scrollTop; | |
if (that.scrollTop > 60) { | |
that.btnFlag = true; | |
} else { | |
that.btnFlag = false; | |
} | |
}, | |
}, | |
}; | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Template部分使用Vuetify框架。将本组件加载到Vue根组件上即可。