在 UniApp 中,下拉刷新和上拉加载是常见的列表交互功能。UniApp 提供了内置的组件和 API 来实现这些功能,开发者可以轻松地为页面添加下拉刷新和上拉加载的效果。
一、下拉刷新
1. 启用下拉刷新
- 在
pages.json
中为页面配置enablePullDownRefresh
属性。 - 示例:
{ "pages": [ { "path": "pages/index/index", "style": { "enablePullDownRefresh": true } } ] }
2. 监听下拉刷新事件
- 在页面中使用
onPullDownRefresh
生命周期函数监听下拉刷新事件。 - 示例:
export default { onPullDownRefresh() { console.log('下拉刷新触发'); // 模拟数据加载 setTimeout(() => { uni.stopPullDownRefresh(); // 停止下拉刷新 }, 1000); } };
3. 停止下拉刷新
- 使用
uni.stopPullDownRefresh
停止下拉刷新的动画。 - 示例:
uni.stopPullDownRefresh();
二、上拉加载
1. 监听上拉加载事件
- 在页面中使用
onReachBottom
生命周期函数监听上拉加载事件。 - 示例:
export default { data() { return { list: [], page: 1, hasMore: true }; }, onReachBottom() { if (this.hasMore) { this.loadMoreData(); } }, methods: { loadMoreData() { console.log('上拉加载触发'); // 模拟数据加载 setTimeout(() => { const newData = Array.from({ length: 10 }, (_, i) => `Item ${this.list.length i 1}`); this.list = this.list.concat(newData); this.page ; if (this.page >= 5) { this.hasMore = false; // 没有更多数据 } }, 1000); } } };
2. 显示加载状态
- 使用
uni.showLoading
和uni.hideLoading
显示加载状态。 - 示例:
uni.showLoading({ title: '加载中...' }); setTimeout(() => { uni.hideLoading(); }, 1000);
三、完整示例
以下是一个完整的示例,展示了如何实现下拉刷新和上拉加载:
1. pages.json
配置
{
"pages": [
{
"path": "pages/index/index",
"style": {
"enablePullDownRefresh": true
}
}
]
}
2. 页面代码
<template>
<view>
<view v-for="(item, index) in list" :key="index" class="item">
{{ item }}
</view>
<view v-if="!hasMore" class="no-more">没有更多数据了</view>
</view>
</template>
<script>
export default {
data() {
return {
list: [],
page: 1,
hasMore: true
};
},
onLoad() {
this.loadData();
},
onPullDownRefresh() {
console.log('下拉刷新触发');
this.page = 1;
this.hasMore = true;
this.loadData();
},
onReachBottom() {
if (this.hasMore) {
this.loadMoreData();
}
},
methods: {
loadData() {
// 模拟数据加载
setTimeout(() => {
this.list = Array.from({ length: 10 }, (_, i) => `Item ${i 1}`);
uni.stopPullDownRefresh();
}, 1000);
},
loadMoreData() {
console.log('上拉加载触发');
uni.showLoading({ title: '加载中...' });
setTimeout(() => {
const newData = Array.from({ length: 10 }, (_, i) => `Item ${this.list.length i 1}`);
this.list = this.list.concat(newData);
this.page ;
if (this.page >= 5) {
this.hasMore = false;
}
uni.hideLoading();
}, 1000);
}
}
};
</script>
<style>
.item {
padding: 20px;
border-bottom: 1px solid #eee;
}
.no-more {
text-align: center;
padding: 20px;
color: #999;
}
</style>
四、总结
UniApp 提供了简单易用的方式来实现下拉刷新和上拉加载:
- 下拉刷新:通过
enablePullDownRefresh
和onPullDownRefresh
实现。 - 上拉加载:通过
onReachBottom
实现。 - 加载状态:使用
uni.showLoading
和uni.hideLoading
显示加载状态。
通过合理使用这些功能,可以提升列表页面的交互体验,满足用户对数据刷新的需求。
完整内容可以查看我的公众号文章:UniApp 如何实现下拉刷新和上拉加载?()。
原文出处:
内容由AI生成仅供参考,请勿使用于商业用途。如若转载请注明原文及出处。
出处地址:http://www.07sucai.com/tech/527.html
版权声明:本文来源地址若非本站均为转载,若侵害到您的权利,请及时联系我们,我们会在第一时间进行处理。