feat: 更新无限加载组件
All checks were successful
/ build-and-deploy-to-vercel (push) Successful in 1m24s
/ playwright (push) Successful in 2m6s
/ depcheck (push) Successful in 1m38s

This commit is contained in:
严浩
2024-12-08 00:04:31 +08:00
parent 2574e38d9a
commit 5f98fe12ba
4 changed files with 55 additions and 127 deletions

View File

@ -17,15 +17,22 @@ function checkIsVisible(el: Element, root: Element | null = null) {
</script>
<script setup lang="ts">
const target = ref(null);
// defineSlots
const state = ref<'' | 'loading' | 'loaded' | 'complete' | 'error'>(''); // TODO: use ts-enum-util
const props = defineProps<{
asyncLoad: () => Promise<{ hasMore: boolean }>;
}>();
defineSlots<{
loading(): unknown;
complete(): unknown;
error(props: { retry: () => void }): unknown;
}>();
const load = async () => {
const target = ref(null);
const state = ref<'' | 'loading' | 'loaded' | 'complete' | 'error'>(''); // TODO: use ts-enum-util
const load = async (why?: string) => {
console.group('load');
console.debug(`why :>> `, why);
console.groupEnd();
if (state.value === 'loading') return;
state.value = 'loading';
@ -35,7 +42,7 @@ const load = async () => {
if (hasMore) {
await nextTick();
if (checkIsVisible(target.value!)) {
load();
load('visible after load');
}
}
@ -51,7 +58,7 @@ const { pause /* , resume, isSupported, isActive */ } = useIntersectionObserver(
target,
([entry]) => {
if (entry?.isIntersecting) {
load();
load('visible in observer');
}
},
{
@ -66,21 +73,45 @@ const { pause /* , resume, isSupported, isActive */ } = useIntersectionObserver(
<template>
<div class="infinite-loading" ref="target">
<slot v-if="state === 'complete'" name="complete">
<span>没有更多了</span>
</slot>
<div v-if="state === 'complete'" class="infinite-loading__complete">
<slot name="complete">
<span>没有更多了</span>
</slot>
</div>
<template v-else>
<div v-show="state == 'loading'">
<div v-show="state == 'loading'" class="infinite-loading__loading">
<slot name="loading">
<span> 加载中... </span>
</slot>
</div>
<slot v-if="state === 'error'" name="error">
<div>
<span> 加载失败 </span>
<button @click="load">重试</button>
</div>
</slot>
<div
v-if="state === 'error'"
class="infinite-loading__error"
@click="
() => {
!$slots.error && load('click error');
}
"
>
<slot name="error" :retry="load">
<span> 加载失败点击重试 </span>
</slot>
</div>
</template>
</div>
</template>
<style scoped>
.infinite-loading__loading,
.infinite-loading__complete,
.infinite-loading__error {
display: flex;
justify-content: center;
align-items: center;
min-height: 40px;
color: #666;
}
.infinite-loading__error {
cursor: pointer;
}
</style>

View File

@ -5,7 +5,7 @@ const DEBUG_MAX_PAGE = 5;
let page = 0;
const list = ref<Record<string, never>[]>([]);
const loadData = async () => {
await new Promise((resolve) => setTimeout(resolve, 1250));
await new Promise((resolve) => setTimeout(resolve, 250 /* + 1000 */));
if (page === 1 && showDebugError) {
showDebugError = false;
throw new Error('Failed to load comments');
@ -26,7 +26,9 @@ const loadData = async () => {
<p class="mt-[8px]">{{ item.body }}</p>
</template>
</Card>
<UseIntersectionObserverInfiniteLoading :async-load="loadData" />
<UseIntersectionObserverInfiniteLoading :async-load="loadData">
<template #error="{ retry }">
<Button fluid @click="retry">Retry</Button>
</template>
</UseIntersectionObserverInfiniteLoading>
</template>
<style scoped></style>

View File

@ -1,104 +0,0 @@
<script setup lang="ts">
import { useIntersectionObserver } from '@vueuse/core';
import { ref } from 'vue';
function checkIsVisible(el: Element, root: Element | null = null) {
if (!el) return false;
const elRect = el.getBoundingClientRect();
const rootRect = root
? root.getBoundingClientRect()
: { top: 0, left: 0, bottom: window.innerHeight, right: window.innerWidth };
return (
elRect.bottom >= rootRect.top &&
elRect.top <= rootRect.bottom &&
elRect.right >= rootRect.left &&
elRect.left <= rootRect.right
);
}
interface Comment {
postId: number;
id: number;
name: string;
email: string;
body: string;
}
const list = ref<Comment[]>([]);
const loading = ref(false);
const page = ref(0);
const pageSize = 1;
const loadMore = async () => {
if (loading.value) return;
loading.value = true;
try {
await new Promise((resolve) => setTimeout(resolve, 1000));
const response = await fetch(
`https://jsonplaceholder.typicode.com/comments?_page=${++page.value}&_limit=${pageSize}`,
);
const data = await response.json();
list.value.push(...data);
} catch (error) {
console.error('Failed to load comments:', error);
} finally {
loading.value = false;
}
await nextTick();
if (checkIsVisible(target.value!)) {
loadMore();
}
};
const target = ref(null);
const isVisible = ref(false);
const { isActive, pause, resume, isSupported } = useIntersectionObserver(
target,
([entry]) => {
isVisible.value = entry?.isIntersecting || false;
if (entry?.isIntersecting) {
loadMore();
}
},
// { threshold: 0.1 },
);
</script>
<template>
<Card v-for="item in list" :key="item.id" class="mb-[16px]">
<template #title>{{ item.name }}</template>
<template #content>
<p class="text-gray-600">{{ item.email }}</p>
<p class="mt-[8px]">{{ item.body }}</p>
</template>
</Card>
<div ref="target" class="border-[8px] border-blue-500 p-[16px]">
<Button label="Load more" :loading="loading" fluid @click="loadMore" />
</div>
<ScrollTop />
<div class="border-[1px] border-blue-500 fixed top-16 right-16 p-[4px] bg-white" flex="~ col" items-end>
<label class="checkbox">
<span mr="[8px]">isSupported: {{ isSupported }}</span>
<input
:checked="isActive"
type="checkbox"
name="enabled"
@input="($event.target as HTMLInputElement)!.checked ? resume() : pause()"
/>
<span>Enable</span>
</label>
<div>
Element
<span class="font-bold" :class="isVisible ? 'text-blue-500' : 'text-orange-400'">
{{ isVisible ? 'inside' : 'outside' }}
</span>
the viewport
</div>
</div>
</template>

3
typed-router.d.ts vendored
View File

@ -25,10 +25,9 @@ declare module 'vue-router/auto-routes' {
'Api': RouteRecordInfo<'Api', '/api', Record<never, never>, Record<never, never>>,
'DataLoadersId': RouteRecordInfo<'DataLoadersId', '/data-loaders/:id', { id: ParamValue<true> }, { id: ParamValue<false> }>,
'IndexPage': RouteRecordInfo<'IndexPage', '/index-page', Record<never, never>, Record<never, never>>,
'InfiniteLoading': RouteRecordInfo<'InfiniteLoading', '/InfiniteLoading', Record<never, never>, Record<never, never>>,
'InfiniteLoading': RouteRecordInfo<'InfiniteLoading', '/infinite-loading', Record<never, never>, Record<never, never>>,
'MdPage': RouteRecordInfo<'MdPage', '/md-page', Record<never, never>, Record<never, never>>,
'SomePage': RouteRecordInfo<'SomePage', '/some-page', Record<never, never>, Record<never, never>>,
'TsEnumUtil': RouteRecordInfo<'TsEnumUtil', '/ts-enum-util', Record<never, never>, Record<never, never>>,
'UseIntersectionObserverList': RouteRecordInfo<'UseIntersectionObserverList', '/useIntersectionObserverList', Record<never, never>, Record<never, never>>,
}
}