一、封装组件
javascript
<template>
<u-transition mode="fade" :show="show">
<view class="back-bottom" @click="scrollToBottom">
<u-icon name="arrow-downward" size="18" color="#909399"></u-icon>
<text>底部</text>
</view>
</u-transition>
</template>
<script>
export default {
name: "BackBottom",
props: {
bottom: {
type: Number,
default: 100
}
},
data() {
return {
pageHeight: 0,
scrollHeight: 0,
diffHeight: this.bottom + 1, // 初始值大于bottom,防止首次渲染不显示
};
},
computed: {
show() {
return this.diffHeight < this.bottom ? false : true;
},
},
mounted() {
this.pageHeight = document.documentElement.scrollHeight; // 当前页面高度
window.addEventListener('scroll', this.updateScrollHeight);
},
beforeDestroy() {
window.removeEventListener('scroll', this.updateScrollHeight);
},
methods: {
updateScrollHeight() {
let clientHeight = document.documentElement.clientHeight; // 当前屏幕高度
this.scrollHeight = window.scrollY; // 页面滚动高度
this.diffHeight = this.pageHeight - (this.scrollHeight + clientHeight);
},
scrollToBottom() {
uni.pageScrollTo({
scrollTop: this.pageHeight,
duration: 100
});
}
}
}
</script>
<style lang="scss" scoped>
.back-bottom{
width: 40px;
height: 40px;
border-radius: 8rpx;
background: #e1e1e1;
position: fixed;
bottom: 100rpx;
right: 20px;
box-shadow: 0px 0px 16px 1px rgba(119, 119, 119, 0.1);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
font-size: 24rpx;
}
</style>
二、使用组件
javascript
<back-bottom />
<back-bottom bottom="100"/>