feat: 添加路由元信息支持,优化无限加载组件的状态管理和错误处理
Some checks failed
/ build-and-deploy-to-vercel (push) Successful in 55s
/ depcheck (push) Successful in 1m24s
/ playwright (push) Failing after 2m50s

This commit is contained in:
严浩
2025-01-08 14:43:26 +08:00
parent d4b34a4f1f
commit 7258853b57
8 changed files with 204 additions and 144 deletions

View File

@ -1,5 +1,10 @@
<script setup lang="ts">
const route = useRoute();
definePage({
meta: {
hidden: true,
},
});
</script>
<template>

View File

@ -1,75 +1,130 @@
<script lang="ts">
import { toRaw } from 'vue';
const structuredClone = window.structuredClone || ((obj) => JSON.parse(JSON.stringify(obj)));
const K_INITIAL_CACHE = deepFreeze({
page: 0,
const K_INITIAL_STATE = deepFreeze({
list: [] as Record<string, never>[],
hasMore: true,
page: 0,
loading: false,
complete: false,
error: null as unknown,
});
const cache = structuredClone(K_INITIAL_CACHE);
const updateCache = (newCache: typeof cache) =>
Object.assign(cache, Object.fromEntries(Object.entries(newCache).map(([key, value]) => [key, toRaw(value)])));
const clearCache = () => Object.assign(cache, structuredClone(K_INITIAL_CACHE));
// XXX: 可以直接把 list 定义在这上面???
let page3ShouldError = true;
const state = shallowReactive(structuredClone(K_INITIAL_STATE));
</script>
<script setup lang="ts">
defineOptions({
beforeRouteEnter: (to, from) => {
if (from.name !== 'InfiniteLoadingDetail') clearCache(); // 如果来的页面不是详情页,清空缓存。
if (from.name !== 'InfiniteLoadingDetail') {
Object.assign(state, structuredClone(K_INITIAL_STATE));
}
},
beforeRouteLeave: (to, from) => {
if (to.name !== 'InfiniteLoadingDetail') clearCache(); // 如果去的页面不是详情页,清空缓存。
if (to.name !== 'InfiniteLoadingDetail') {
Object.assign(state, structuredClone(K_INITIAL_STATE));
}
},
});
let isPage2ErrorVisible = true;
const lastCache = structuredClone(cache); // 要在 `loadData` 之前获取,因为 `loadData` 会修改 `cache.page`。
const list = shallowRef<Record<string, never>[]>(lastCache.list);
const loadData = async (page: number) => {
if (!lastCache.hasMore) return { hasMore: false };
const newPage = page + lastCache.page;
await new Promise((resolve) => setTimeout(resolve, 250 + 1000));
if (newPage === 2 && isPage2ErrorVisible) {
isPage2ErrorVisible = false;
throw new Error('Failed to load comments. Because page === 2');
}
const response = await fetch(
`https://jsonplaceholder.typicode.com/comments?_page=${newPage}&_limit=1&timestamp=${Date.now()}`,
);
const data = await response.json();
list.value = list.value.concat(data);
const hasMore = list.value.length < 5;
updateCache({ page: newPage, list: list.value, hasMore });
return { hasMore };
const refresh = () => {
state.list.splice(0, state.list.length);
state.page = 0;
state.complete = false;
loadMore();
};
async function loadMore() {
if (state.loading) return;
try {
state.loading = true;
const response = await fetch(
`https://jsonplaceholder.typicode.com/comments?_page=${++state.page}&_limit=1&timestamp=${Date.now()}`,
).then((res) => {
if (state.page === 3 && page3ShouldError) {
page3ShouldError = false;
throw new Error('test error');
} else {
return res;
}
});
const data = await response.json();
state.list = state.list.concat(data);
if ($__DEV__) await new Promise((resolve) => setTimeout(resolve, 500));
state.complete = state.list.length >= 5;
} catch (error) {
state.error = error;
state.page--;
} finally {
state.loading = false;
}
}
type CurrentUse = 'van-list' | 'use-intersection-observer-infinite-loading';
const currentUse = ref<CurrentUse>((sessionStorage.getItem('currentUse') as CurrentUse) || 'van-list');
watchEffect(() => {
sessionStorage.setItem('currentUse', currentUse.value);
});
</script>
<template>
<Button label="刷新" @click="list.splice(0, list.length) && $refs.infiniteLoading?.refresh()" mb-4 />
<Card
v-for="item in list"
:key="item.id"
class="mb-[16px]"
@click="$router.push({ name: 'InfiniteLoadingDetail', query: { id: item.id } })"
>
<template #title>{{ item.name }}</template>
<template #content>
<p class="mt-[8px]">{{ item.body }}</p>
</template>
<template #subtitle>id:{{ item.id }} </template>
<template #footer>{{ item.email }}</template>
</Card>
<div border="1 px solid red">
{{ { 'list.length': list.length } }}
<div mb-4 class="flex justify-end gap-4 flex-wrap items-start">
<Button label="刷新" @click="refresh" />
<Button
label="push"
@click="state.list.push({ id: state.list.length + 1, name: 'name', body: 'body', email: 'email' } as any)"
/>
<Button
:label="currentUse"
@click="currentUse = currentUse === 'van-list' ? 'use-intersection-observer-infinite-loading' : 'van-list'"
class="mb-4"
/>
</div>
<UseIntersectionObserverInfiniteLoading :async-load="loadData" ref="infiniteLoading">
<!-- <template #error="{ retry }">
<Button fluid @click="retry">Retry</Button>
</template> -->
</UseIntersectionObserverInfiniteLoading>
<template v-if="currentUse === 'van-list'">
<VanList
@load="loadMore"
:loading="state.loading"
:error="!!state.error"
:error-text="`${state.error}`"
:onUpdate:error="() => (state.error = null)"
:finished="state.complete"
>
<template v-for="item in state.list" :key="item.id">
<div
class="border p-4 mb-[16px]"
@click="$router.push({ name: 'InfiniteLoadingDetail', query: { id: item.id } })"
>
<div>id:{{ item.id }}</div>
</div>
</template>
</VanList>
</template>
<template v-if="currentUse === 'use-intersection-observer-infinite-loading'">
<Card
v-for="item in state.list"
:key="item.id"
class="mb-[16px]"
@click="$router.push({ name: 'InfiniteLoadingDetail', query: { id: item.id } })"
>
<template #title>{{ item.name }}</template>
<template #content>
<p class="mt-[8px]">{{ item.body }}</p>
</template>
<template #subtitle>id:{{ item.id }} </template>
<template #footer>{{ item.email }}</template>
</Card>
<UseIntersectionObserverInfiniteLoading
@load="loadMore"
:loading="state.loading"
:error="!!state.error"
:error-text="`${state.error}`"
@clickError="state.error = null"
:complete="state.complete"
/>
<div border="1 px solid red rounded-lg" class="p-4 mb-[16px]">
{{ { 'list.length': state.list.length } }}
</div>
</template>
<ScrollTop />
</template>