在本章节,我们重点学习如何做上拉加载更多。
接口地址:https://www.yuque.com/xiumubai/fe/yf8tf3#oV4jG

定义接口

  1. import Service from '@/utils/http';
  2. class Course extends Service {
  3. /**
  4. * @description: 获取课程列表
  5. * @param {*} options
  6. * @return {*}
  7. */
  8. courseList(options = {}) {
  9. options.url = `/api/edu/course/${options.page}/${options.limit}`;
  10. return this.get(options);
  11. }
  12. }
  13. const courseService = new Course();
  14. export default courseService;

请求接口

  1. <script>
  2. import courseService from "@/services/course";
  3. export default {
  4. data() {
  5. return {
  6. list: [],
  7. params: {
  8. page: 1,
  9. limit: 10,
  10. },
  11. status: "more",
  12. };
  13. },
  14. onLoad() {
  15. this.getCourseList();
  16. },
  17. /**
  18. * @description: 监听触底事件,最外层view不能添加css样式overflow:scroll
  19. * @returns {*}
  20. */
  21. onReachBottom() {
  22. if (this.status !== "noMore") {
  23. this.status = "loading";
  24. this.params.page++;
  25. this.getCourseList();
  26. }
  27. },
  28. methods: {
  29. async getCourseList() {
  30. try {
  31. const res = await courseService.courseList({
  32. ...this.params,
  33. });
  34. const items = res.data.items;
  35. // 数组解构拼接
  36. this.list = [...this.list, ...items];
  37. if (items.length < 10) return (this.status = "noMore");
  38. if (items.length >= 10) this.status = "more";
  39. } catch (e) {
  40. console.log("e", e);
  41. }
  42. },
  43. },
  44. };
  45. </script>
  • 默认onLoad的时候请求一次数据
  • 监听onReachBottom事件,当触底的时候再次请求数据,这时候page+1,status显示状态为loading
  • 请求到的数据利用数组接口的方式进行拼接
  • 当本次请求数据<每页条数(默认10条),说明服务端数据加载完了,status显示状态为noMore
  • 当本次请求数据>=每页条数(默认10条),说明服务端数据未完,上拉可以继续加载更多数据,status显示状态为more

    页面渲染

    1. <template>
    2. <view class="course_list">
    3. <view class="course_list_item" v-for="item in list" :key="item.id">
    4. <navigator
    5. class="course_list_item_a"
    6. :url="'/pages/course/detail?id=' + item.id"
    7. >
    8. <view class="item_cover">
    9. <image :src="item.cover" />
    10. </view>
    11. <view class="item_content">
    12. <h3 class="content_title">{{ item.title }}</h3>
    13. <view class="content_price">
    14. <view class="price">¥{{ item.price }}</view>
    15. <view class="buy_num">{{ item.buyCount }}人已购买</view>
    16. </view>
    17. </view>
    18. </navigator>
    19. </view>
    20. <!-- 加载更多 -->
    21. <view class="load_more">
    22. <uni-load-more :status="status" />
    23. </view>
    24. </view>
    25. </template>
    对于我的订单和我的收藏页面,除了接口url和样式不一致以外,其他的完全一个套路,
    具体可以参考代码:
    我的订单src/pages/order/list.vue
    我的收藏src/pages/course/collect.vue