CourseListPage.vue 2.56 KB
<!--
 * @Date: 2025-03-21 14:31:21
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2025-05-21 16:57:36
 * @FilePath: /mlaj/src/views/courses/CourseListPage.vue
 * @Description: 文件描述
-->
<template>
  <AppLayout title="课程列表">
    <div class="pb-16">
      <!-- Search Bar -->
      <div class="pb-2">
        <SearchBar placeholder="搜索" v-model="keyword" @blur="handleBlur" />
      </div>

      <!-- Course List -->
      <div class="px-4">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多课程了"
          @load="onLoad"
          class="space-y-4"
        >
          <CourseCard v-for="course in courses" :key="course.id" :course="course" />
        </van-list>
      </div>
    </div>
  </AppLayout>
</template>

<script setup>
import { ref, onMounted, watchEffect } from 'vue';
import { useRoute } from 'vue-router';
import AppLayout from '@/components/layout/AppLayout.vue';
import SearchBar from '@/components/ui/SearchBar.vue';
import CourseCard from '@/components/ui/CourseCard.vue';
import { courses as mockCourses } from '@/utils/mockData';
// 导入接口
import { getCourseListAPI } from "@/api/course";
import { List } from 'vant';
import { useDebounceFn } from '@vueuse/core';

const $route = useRoute();
const courses = ref([]);
const loading = ref(false);
const finished = ref(false);
const limit = ref(5);
const page = ref(0);
const keyword = ref('');

// 防抖处理的搜索课程列表
const debouncedSearch = useDebounceFn(async (searchKeyword) => {
  const res = await getCourseListAPI({ limit: limit.value, page: 0, keyword: searchKeyword });
  if (res.code) {
    courses.value = res.data;
    finished.value = res.data.length < limit.value;
    page.value = 1;
  }
}, 300);

// 统一处理搜索操作
const handleSearch = (newKeyword) => {
  if (keyword.value !== newKeyword) {
    keyword.value = newKeyword;
    debouncedSearch(newKeyword);
  }
};

// 监听路由参数变化
watchEffect(() => {
  const queryKeyword = $route.query.keyword;
  if (queryKeyword !== undefined) {
    handleSearch(queryKeyword || '');
  }
});

// Blur handler
const handleBlur = (query) => {
  handleSearch(query);
};

// Load more courses
const onLoad = async () => {
  const nextPage = page.value;
  const res = await getCourseListAPI({ limit: limit.value, page: nextPage, keyword: keyword.value });
  if (res.code) {
    courses.value = [...courses.value, ...res.data];
    finished.value = res.data.length < limit.value;
    page.value = nextPage + 1;
  }
  loading.value = false;
};
</script>