uniapp下拉刷新和上拉加载更多

本示例提供了一个使用uni-app实现的下拉刷新和上拉加载更多功能的代码模板。通过调整状态和数据加载逻辑,可以轻松地为列表组件添加刷新和加载更多功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<template>
	<!-- 下拉刷新和上拉加载更多模板 uniapp 作者@cy -->
	<view class="load_more">
		<div style="background-color: antiquewhite;text-align: center;font-size: 24rpx; color: gray;">下拉刷新数据</div>
		<div v-for="item in dataList" style="height: 280rpx;border-bottom: 1px solid red;">
			{{item.id}}
		</div>
		<uni-load-more :status="status" :icon-size="14" :content-text="contentText" v-if="dataList.length > 0" />
	</view>

</template>

<script>
	import {
		getDataList
	} from '@/api/product'

	export default {
		data() {
			return {
				dataList: [
					{
						id: 1
					},
					{
						id: 1
					},{
						id: 1
					},{
						id: 1
					},{
						id: 1
					},{
						id: 1
					},{
						id: 1
					}
				],
				totalCount: 14, //接口请求到的数据量(展示数据用页码形式),
				params:{
					curretPage: 0, //页码
					pageSize: 10 //页大小
				},
				reload: false, //刷新标志符
				status: 'more',
				contentText: {
					contentdown: '上拉加载更多~',
					contentrefresh: '加载中',
					contentnomore: '我是有底线的~'
				},
			}
		},
		onLoad(){
			
		},
		onPullDownRefresh() {
			//初始化信息
            this.dataList = []
			this.params.curretPage = 0,
			this.pageSize = 10
			this.reload = true
			setTimeout(() => {
				this.getData()
			}, 1000)
		},
		onReachBottom() {
			if (this.totalCount > this.dataList.length) {
				this.status = 'loading';
				setTimeout(() => {
					this.getData(); //执行的方法
				}, 1000) //这里我是延迟一秒在加载方法有个loading效果,如果接口请求慢的话可以去掉
			} else { //停止加载
				this.status = 'noMore'
			}
		},
		methods: {
			getData(){
				// getDataList({
				// 	page: this.params.curretPage+1, //请求页码每次+1
				// 	pageSize: this.params.pageSize
				// }).then(res => {
				// 	this.totalCount = res.total
				// 	if (res.total > 0) {
				// 		const dataMap = result.data.list
				// 		this.dataList = this.reload ? dataMap : this.dataList.concat(dataMap);
				// 		this.reload = false;
				//		this.status = 'more'
				// 	} else {
				// 		this.dataList = [];
				// 	}
				// 	if (this.totalCount == this.dataList.length) {
				// 		this.reload = false;
				// 		this.status = 'noMore'
				// 	}
				// })
				let mockData = [
					{
						id:2
					},
					{
						id:2
					}
				]
				this.dataList = this.dataList.concat(mockData)
				this.status = 'more'
				console.log(this.dataList,23333)
				uni.stopPullDownRefresh()
			}
		}
	}
</script>

<style lang="scss" scoped>
	.load_more{
		height: 100%;
	}
</style>

page.json配置

{
			"path": "pages/test/scrollTab",
			"style": {
				"navigationBarTitleText": "scrollTabTest",
				"disableScroll": true,
				"app-plus": {
					"bounce": "none"
				}
			}
		},

### 如何在 UniApp 中实现上拉刷新下拉加载功能 #### 一、基础概念 在 UniApp 的开发中,`uni.startPullDownRefresh()` 是用于触发下拉刷新的核心 API[^1]。它能够模拟用户的下拉操作并启动刷新动画。与此同时,为了满足更复杂的应用场景需求,通常会结合第三方组件 `mescroll-uni` 来完成更加优雅的上下滑动交互体验[^3]。 #### 二、具体实现方式 ##### 方法一:原生 API 实现 利用 UniApp 提供的基础能力来构建简单的上拉加载下拉刷新逻辑: ```javascript // 页面初始化配置 export default { data() { return { listData: [], // 数据列表 page: 1, // 当前页码 pageSize: 10 // 每页大小 }; }, onReachBottom() { // 上拉触底事件 this.loadMore(); }, onPullDownRefresh() { // 下拉刷新事件 this.refreshList(); }, methods: { refreshList() { setTimeout(() => { this.page = 1; this.listData = []; this.fetchData(); // 调用接口获取新数据 uni.stopPullDownRefresh(); // 停止刷新状态 }, 1000); }, loadMore() { this.page++; this.fetchData(); }, fetchData() { let params = { page: this.page, size: this.pageSize }; // 模拟网络请求 setTimeout(() => { const newData = Array.from({ length: this.pageSize }).map((_, i) => `${this.page}-${i}` ); if (newData.length === 0) { console.log('没有更多数据'); return; } this.listData.push(...newData); // 将新的数据追加到已有数组后面 }, 500); } } }; ``` 上述代码展示了基于页面生命周期函数 `onReachBottom` `onPullDownRefresh` 的基本处理流程[^4]。 ##### 方法二:借助 mescroll-uni 组件优化用户体验 对于更高阶的功能需求或者希望减少重复编码工作量的情况下,推荐引入专门设计好的滚动控件库 —— **Mescroll**。该工具不仅封装好了常见的分页机制还提供了丰富的定制选项使得开发者可以根据实际情况灵活调整样式表现形式以及性能参数设置等细节部分。 安装步骤如下所示: 1. 打开 HBuilderX 插件商店搜索关键字 “mescroll”,找到对应版本号点击安装按钮; 2. 成功之后可以在项目的 components 文件夹里面发现新增了一个叫做 'mescroll-uni' 的子目录结构; 接下来按照官方文档指引修改模板布局文件内容如下: ```html <template> <view class="content"> <!-- 配置 Mescroll ScrollView --> <mescroll-body ref="mescrollRef" @init="mescrollInit" :up="upOption" :down="downOption"> <block v-for="(item,index) in dataList" :key="index">{{ item }}</block> </mescroll-body> </view> </template> <script> import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js"; export default { mixins:[MescrollMixin], // 使用混入模式集成核心业务逻辑 data(){ return{ dataList:[], downOption:{ auto:false // 是否自动执行第一次下拉动作,默认关闭防止不必要的资源消耗 }, upOption:{ use:true, // 启用上传模块开关标志位 page:{size:10}, // 初始化每一页显示条目数量限制条件 noMoreSize:5 // 如果剩余不足五项则提示已经到达底部尽头位置信息给用户查看 } } }, methods:{ async downCallback(mescroll){ try{ await new Promise(resolve=>setTimeout(resolve,1e3)); this.dataList=[]; this.upLoadData(mescroll,'reset'); }catch(err){} }, async upLoadData(mescroll,type='add'){ try{ let res=await fetch(`https://example.com/api?page=${type==='reset'?1:mescroll.num}&limit=${mescroll.size}`); let json=res.json(); if(type=='reset')this.dataList=json.results||[]; else this.dataList=[...this.dataList,...(json.results||[])]; mescroll.endSuccess(json.total||0); }catch(e){mescroll.endErr();} } } } </script> ``` 以上片段重点在于通过 Vue Mixin 技术简化了原本繁杂的手写控制流管理过程,并且充分利用异步编程优势进一步提升了程序可读性维护便利程度。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值