需求分析
页面向下滑动到一定距离时显示按钮,点击按钮可以一键到底,一键刷新,向上滑动到一定距离时按钮消失
需求实现
思路方法:封装一个组件,两个按钮:一键到顶和一键刷新按钮。在父页面引用组件,然后在父页面的onPageScroll事件中监听滚动高度,控制组件显隐。
核心功能:利用uniapp的onPageScroll
文档介绍: uni.pageScrollTo(OBJECT) | uni-app官网 (dcloud.net.cn)
uni.pageScrollTo(OBJECT)
将页面滚动到目标位置。
平台差异说明
App | H5 | 微信小程序 | 支付宝小程序 | 百度小程序 | 字节跳动小程序、飞书小程序 | QQ小程序 | 华为快应用 | 360小程序 |
---|---|---|---|---|---|---|---|---|
√(nvue不支持) | √ | √ | √ | √ | √ | √ | √ | √ |
OBJECT参数说明
参数名 | 类型 | 必填 | 说明 |
---|---|---|---|
scrollTop | Number | 否 | 滚动到页面的目标位置(单位px) |
selector | String | 否 | 选择器,App、H5、微信小程序2.7.3+ 、支付宝小程序1.20.0+支持 |
duration | Number | 否 | 滚动动画的时长,默认300ms,单位 ms |
success | function | 否 | 接口调用成功的回调函数 |
fail | function | 否 | 接口调用失败的回调函数 |
complete | function | 否 | 接口调用结束的回调函数(调用成功、失败都会执行) |
selector 语法 selector类似于 CSS 的选择器,但仅支持下列语法。
- ID选择器:#the-id
- class选择器(可以连续指定多个):
.a-class.another-class
- 子元素选择器:
.the-parent > .the-child
- 后代选择器:
.the-ancestor .the-descendant
- 跨自定义组件的后代选择器:
.the-ancestor >>> .the-descendant
- 多选择器的并集:
#a-node, .some-other-nodes
示例:
uni.pageScrollTo({
scrollTop: 0,
duration: 300
});
封装组件如下:
<template>
<view class="flex-column btns-wrap">
<u-icon v-if="isToTop"
name="arrow-upward"
size="40"
class="co-primary plr-8 ptb-8"
@click="toTop"></u-icon>
<view v-if="isRefresh" class="mid-line"></view>
<u-icon v-if="isRefresh"
name="reload"
size="40"
class="co-primary plr-8 ptb-8"
@click="refresh"></u-icon>
</view>
</template>
<script>
export default {
props: {
isToTop: { // 控制一键到顶按钮显隐
type: Boolean,
default: true
},
isRefresh: { // 控制一键刷新按钮显隐
type: Boolean,
default: true
},
},
methods: {
// 一键到顶,支持自定义duration
toTop(duration) {
uni.pageScrollTo({
scrollTop: 0,
duration: (duration === 0 || duration) ? duration : 500
})
},
// 一键刷新,传递事件给父组件
refresh() {
this.$emit('refresh');
}
},
}
</script>
<style lang="scss">
.btns-wrap {
position: fixed;
background: rgba(255, 255, 255, 0.8);
border-radius: 60rpx;
bottom: 200rpx;
right: 60rpx;
box-shadow: 0 0 4px 1px #f0f0f0;
z-index: 998;
}
.mid-line {
border-bottom: 2rpx solid #f0f0f0;
}
</style>
父页面:
<template>
<view>
<TopAndRefresh ref="topAndRefreshRef" v-if="isTopAndRefresh" @refresh="fetchList" />
</view>
</template>
<script>
import TopAndRefresh from '../components/topAndRefresh.vue'
export default {
components: {
TopAndRefresh
},
data() {
return {
isTopAndRefresh: false,
}
},
onPageScroll(e) {
this.isTopAndRefresh = e.scrollTop > 500;
},
methods: {
fetchList() {
// 请求
}
}
}
</script>
效果如下: