feat: 更新无限加载组件,添加刷新功能和错误处理,优化加载状态管理
Some checks failed
/ playwright (push) Failing after 1s
/ depcheck (push) Failing after 2s
/ build-and-deploy-to-vercel (push) Failing after 11s

This commit is contained in:
严浩
2024-12-08 16:53:50 +08:00
parent cd1cd72002
commit b18bab4d7c
4 changed files with 623 additions and 517 deletions

View File

@ -21,10 +21,22 @@ const props = defineProps<{
asyncLoad: (page: number) => Promise<{ hasMore: boolean }>;
}>();
defineSlots<{
// 加载中
loading(): unknown;
// 加载完成(还有更多)
loadMore(props: { load: () => void }): unknown;
// 加载完成(没有更多了)
complete(): unknown;
// 加载失败
error(props: { retry: () => void }): unknown;
}>();
defineExpose({
refresh: () => {
currentPage = 0;
state.value = '';
load('refresh');
},
});
const target = ref(null);
let currentPage = 0;
@ -48,7 +60,7 @@ const load = async (why?: string) => {
}
if (!hasMore) {
pause(); // TODO: 下拉刷新后,怎么恢复?
pause();
}
} catch (error) {
currentPage--;
@ -56,7 +68,7 @@ const load = async (why?: string) => {
}
};
const { pause /* , resume, isSupported, isActive */ } = useIntersectionObserver(
const { pause, resume /* ,isSupported, isActive */ } = useIntersectionObserver(
target,
([entry]) => {
if (entry?.isIntersecting) {
@ -64,6 +76,9 @@ const { pause /* , resume, isSupported, isActive */ } = useIntersectionObserver(
}
},
{
immediate: false,
root: undefined,
rootMargin: '0px',
// 数值形式单个值表示目标元素可见部分与整个目标元素的比例。例如threshold: 0.5
// 目标元素可见比例达到 50% 时触发回调。
// 数组形式多个值表示多个可见比例触发点。例如threshold: [0, 0.25, 0.5, 0.75, 1.0]。
@ -71,11 +86,13 @@ const { pause /* , resume, isSupported, isActive */ } = useIntersectionObserver(
threshold: 0,
},
);
onMounted(() => {
resume();
});
</script>
<template>
<div class="infinite-loading" ref="target">
<!-- TODO: unSupport -->
<div v-if="state === 'complete'" class="infinite-loading__complete">
<slot name="complete">
<span>没有更多了</span>
@ -87,6 +104,20 @@ const { pause /* , resume, isSupported, isActive */ } = useIntersectionObserver(
<span> 加载中... </span>
</slot>
</div>
<!-- 如果 isSupportedloaded 状态应该永远不会出现 -->
<div
v-show="state === 'loaded' || state === ''"
class="infinite-loading__loaded"
@click="
() => {
!$slots.loadMore && load('click loadMore');
}
"
>
<slot name="loadMore" :load>
<span> 加载更多 </span>
</slot>
</div>
<div
v-if="state === 'error'"
class="infinite-loading__error"
@ -104,8 +135,9 @@ const { pause /* , resume, isSupported, isActive */ } = useIntersectionObserver(
</div>
</template>
<style scoped>
<style>
.infinite-loading__loading,
.infinite-loading__loaded,
.infinite-loading__complete,
.infinite-loading__error {
display: flex;
@ -114,6 +146,7 @@ const { pause /* , resume, isSupported, isActive */ } = useIntersectionObserver(
min-height: 40px;
color: #666;
}
.infinite-loading__loaded,
.infinite-loading__error {
cursor: pointer;
}