在本章节,我们重点学习如何做上拉加载更多。
接口地址:https://www.yuque.com/xiumubai/fe/yf8tf3#oV4jG
定义接口
import Service from '@/utils/http';
class Course extends Service {
/**
* @description: 获取课程列表
* @param {*} options
* @return {*}
*/
courseList(options = {}) {
options.url = `/api/edu/course/${options.page}/${options.limit}`;
return this.get(options);
}
}
const courseService = new Course();
export default courseService;
请求接口
<script>
import courseService from "@/services/course";
export default {
data() {
return {
list: [],
params: {
page: 1,
limit: 10,
},
status: "more",
};
},
onLoad() {
this.getCourseList();
},
/**
* @description: 监听触底事件,最外层view不能添加css样式overflow:scroll
* @returns {*}
*/
onReachBottom() {
if (this.status !== "noMore") {
this.status = "loading";
this.params.page++;
this.getCourseList();
}
},
methods: {
async getCourseList() {
try {
const res = await courseService.courseList({
...this.params,
});
const items = res.data.items;
// 数组解构拼接
this.list = [...this.list, ...items];
if (items.length < 10) return (this.status = "noMore");
if (items.length >= 10) this.status = "more";
} catch (e) {
console.log("e", e);
}
},
},
};
</script>
- 默认onLoad的时候请求一次数据
- 监听
onReachBottom
事件,当触底的时候再次请求数据,这时候page+1,status显示状态为loading - 请求到的数据利用数组接口的方式进行拼接
- 当本次请求数据<每页条数(默认10条),说明服务端数据加载完了,status显示状态为noMore
- 当本次请求数据>=每页条数(默认10条),说明服务端数据未完,上拉可以继续加载更多数据,status显示状态为more
页面渲染
对于我的订单和我的收藏页面,除了接口url和样式不一致以外,其他的完全一个套路,<template>
<view class="course_list">
<view class="course_list_item" v-for="item in list" :key="item.id">
<navigator
class="course_list_item_a"
:url="'/pages/course/detail?id=' + item.id"
>
<view class="item_cover">
<image :src="item.cover" />
</view>
<view class="item_content">
<h3 class="content_title">{{ item.title }}</h3>
<view class="content_price">
<view class="price">¥{{ item.price }}</view>
<view class="buy_num">{{ item.buyCount }}人已购买</view>
</view>
</view>
</navigator>
</view>
<!-- 加载更多 -->
<view class="load_more">
<uni-load-more :status="status" />
</view>
</view>
</template>
具体可以参考代码:
我的订单src/pages/order/list.vue
我的收藏src/pages/course/collect.vue