封装
hooks/useFetchList.js
import { ref } from "vue";
import { onReachBottom } from "@dcloudio/uni-app";
export function useFetchList(api, initialParams = {}) {
const params = ref({ page: 1, page_size: 20 });
const listData = ref([]);
const isNoData = ref(false);
const loadstatus = ref();
onReachBottom(() => {
fetchList(false);
});
async function fetchList(isReset = true) {
if (isReset) {
resetState();
}
if (isNoData.value) return;
loadstatus.value = "loading";
try {
const response = await api({ ...params.value, ...initialParams });
const { list, count } = response.data;
listData.value = [...listData.value, ...list];
if (list.length === params.value.page_size) {
params.value.page += 1;
loadstatus.value = "more";
} else {
isNoData.value = true;
loadstatus.value = params.value.page == 1 && list.length == 0 ? "first-no-more" : "no-more";
}
} catch (error) {
console.error("Failed", error);
}
try {
} catch (error) {}
}
function resetState() {
params.value.page = 1;
listData.value = [];
isNoData.value = false;
}
return {
listData,
loadstatus,
fetchList,
};
}
页面使用
pages/index.vue
<template>
<view>
<view v-for="(item, index) in listData" :key="item.id"></view>
<noData :loadstatus="loadstatus"></noData>
</view>
</template>
<script setup>
import { useFetchList } from "/hooks/useFetchList";
import { getList } from "/api/index";
const params = reactive({
});
const { listData, loadstatus, fetchList } = useFetchList(getList, params);
onLoad((opt) => {
fetchList();
});
</script>
components/noData.vue
<template>
<view>
<view class="noData" v-if="loadstatus == 'first-no-more'">
<image class="noData-img" src="/static/no-data.png" mode="" />
<view class="cl_999 font-40 text-center">这里什么也没有~</view>
</view>
<uni-load-more :status="loadstatus" v-else></uni-load-more>
</view>
</template>
<script setup>
const props = defineProps({
loadstatus: {
type: String,
default: "",
},
});
</script>
<style lang="scss" scoped>
.noData {
padding-top: 200rpx;
&-img {
width: 544rpx;
height: 412rpx;
display: block;
margin: 0 auto;
}
}
</style>
api/index.js
//模拟请求
export const getList = (params) => () => {
return new Promise((resolve, reject) => {
resolve({
code: 0,
list: params.page == 3 ? [] : new Array(20).fill(null),
});
});
};
标签:uniapp,const,loadstatus,value,listData,params,vue3,page,加载
From: https://blog.csdn.net/kjlkmkl/article/details/144533603