uniapp+vue3页面滚动加载数据

发布于:2025-05-17 ⋅ 阅读:(17) ⋅ 点赞:(0)

1.使用scroll-view

<scroll-view class="scroll-container" scroll-y="true" @scrolltolower="loadMore" :lower-threshold="50">
                < 列表数据写这里>
                
                <!-- 加载提示 -->
                <view v-if="loading" class="loading-container col-span-full text-center py-4">
                    <text class="text-[#fff]">加载提示</text>
                </view>

                <!-- 没有更多数据提示 -->
                <view v-else-if="!hasMore" class="no-more-container col-span-full text-center py-4">
                    <text class="text-[#fff]">没有更多数据提示</text>
                </view>
            </scroll-view>
      js代码--------------------------------------------------------------------------------------
	            // 当前页码
const currentPage = ref(1);
// 每页大小
const pageSize = ref(18);
// 是否正在加载
const loading = ref(false);
// 是否还有更多数据
const hasMore = ref(true);


onMounted(() => {
    coverVideoList();
});

const coverVideoList = async () => {
    // 如果正在加载或没有更多数据,则不执行请求
    if (loading.value || !hasMore.value) return;

    loading.value = true;

    try {
        const {data} = await videoListPost({
            pageNo: currentPage.value,
            pageSize: pageSize.value,
        });

        if (currentPage.value === 1) {
      
            // 第一页数据直接替换  页面数据 productList
            productList.value = data.list || [];
        } else {
            // 非第一页数据追加到列表后面
            productList.value = [...productList.value, ...(data.list || [])];
        }

        // 判断是否还有更多数据
        hasMore.value = data.list && data.list.length === pageSize.value;

        console.log(data.list, "加载的数据");
    } catch (error) {
        console.error("加载数据失败", error);
        // 发生错误时回退页码
        if (currentPage.value > 1) {
            currentPage.value--;
        }
    } finally {
        loading.value = false;
    }
};
// 加载更多数据
const loadMore = () => {
  console.log('到底了吗');
  
    if (!loading.value && hasMore.value) {
        currentPage.value++;
        coverVideoList();
    }
};
css--------------------------------------------------------------------------------
.scroll-container {
    height: calc(100vh - 200rpx); // 减去搜索框的高度
}

网站公告

今日签到

点亮在社区的每一天
去签到