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,12 +1,12 @@
#!/bin/bash #!/bin/bash
echo "🔧 Running pre-commit hook..." echo "🔧 Running pre-commit hook..."
if command -v pnpm >/dev/null 2>&1; then # if command -v pnpm >/dev/null 2>&1; then
# 如果 pnpm 可用,直接使用它 # # 如果 pnpm 可用,直接使用它
pnpm exec lint-staged # pnpm exec lint-staged
else # else
# 如果 pnpm 不可用,使用 $HOME/.local/bin/pnpm # # 如果 pnpm 不可用,使用 $HOME/.local/bin/pnpm
# ln -s $(which pnpm) $HOME/.local/bin/pnpm # # ln -s $(which pnpm) $HOME/.local/bin/pnpm
echo "pnpm not found, using $HOME/.local/bin/pnpm" # echo "pnpm not found, using $HOME/.local/bin/pnpm"
"$HOME"/.local/bin/pnpm exec lint-staged # "$HOME"/.local/bin/pnpm exec lint-staged
fi # fi

View File

@ -47,9 +47,9 @@
<div class="page-wrapper" style="display: flex; justify-content: center; align-items: center">Loading...</div> <div class="page-wrapper" style="display: flex; justify-content: center; align-items: center">Loading...</div>
</div> </div>
<script type="module" src="/src/main.ts"></script> <script type="module" src="/src/main.ts"></script>
<!-- <script src="https://testingcf.jsdelivr.net/npm/@vant/touch-emulator/dist/index.min.js"></script> --> <script src="https://testingcf.jsdelivr.net/npm/@vant/touch-emulator/dist/index.min.js"></script>
<!-- .min.js 是 jsDelivr 的特殊处理 --> <!-- .min.js 是 jsDelivr 的特殊处理 -->
<script src="https://unpkg.luckincdn.com/@vant/touch-emulator@1.4.0/dist/index.js"></script> <!-- <script src="https://unpkg.luckincdn.com/@vant/touch-emulator@1.4.0/dist/index.js"></script> -->
</body> </body>
<script> <script>
(function (d) { (function (d) {

View File

@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
/* https://github.com/youzan/vant/blob/be93d4990fd671338b5d1066cf8419519d668d65/packages/vant/src/list/List.tsx */
function checkIsVisible(el: Element, root: Element | null = null) { function checkIsVisible(el: Element, root: Element | null = null) {
if (!el) return false; if (!el) return false;
@ -26,66 +27,57 @@ function checkIsVisible(el: Element, root: Element | null = null) {
* ``` * ```
* *
* ```vue * ```vue
* <UseIntersectionObserverInfiniteLoading :async-load="loadData" ref="infiniteLoading" /> * <UseIntersectionObserverInfiniteLoading />
* ``` * ```
*/ */
const props = defineProps<{ const props = defineProps<{
asyncLoad: (page: number) => Promise<{ hasMore: boolean }>; loading: boolean;
complete: boolean;
error: boolean;
errorText: string;
}>(); }>();
defineSlots<{ defineSlots<{
// 加载中 // 加载中
loading(): unknown; loading(): unknown;
// 加载完成(还有更多) // 加载完成(还有更多)
loadMore(props: { load: () => void }): unknown; loaded(): unknown;
// 加载完成(没有更多了) // 加载完成(没有更多了)
complete(): unknown; complete(): unknown;
// 加载失败 // 加载失败
error(props: { retry: () => void }): unknown; error(): unknown;
}>(); }>();
defineExpose({
refresh: () => {
currentPage = 0;
state.value = '';
return load('refresh');
},
});
const target = ref(null); const check = (reason?: string) => {
let currentPage = 0; nextTick(() => {
const state = ref<'' | 'loading' | 'loaded' | 'complete' | 'error'>(''); if (
props.loading ||
const load = async (why?: string) => { props.complete ||
console.group('load'); // props.disabled ||
console.debug(`why :>> `, why); props.error
console.groupEnd(); ) {
if (state.value === 'loading') return; return;
state.value = 'loading';
try {
const { hasMore } = await props.asyncLoad(++currentPage);
state.value = hasMore ? 'loaded' : 'complete';
if (hasMore && checkIsVisible(target.value!)) {
await nextTick();
await new Promise((resolve) => setTimeout(resolve, 300));
load('visible after load');
} }
if (checkIsVisible(target.value!)) {
if (!hasMore) { emit('load');
pause();
}
} catch (error) {
console.error(`error :>> `, error);
currentPage--;
state.value = 'error';
} }
});
}; };
const { pause, resume /* ,isSupported, isActive */ } = useIntersectionObserver( const emit = defineEmits<{
load: [];
clickError: [];
}>();
const target = ref(null);
const { pause, resume } = useIntersectionObserver(
target, target,
([entry]) => { ([entry]) => {
if (entry?.isIntersecting) { if (entry?.isIntersecting) {
load('visible in observer'); if (props.loading) return;
check('isIntersecting');
} }
}, },
{ {
@ -99,52 +91,48 @@ const { pause, resume /* ,isSupported, isActive */ } = useIntersectionObserver(
threshold: 0, threshold: 0,
}, },
); );
onMounted(() => { watchEffect(() => {
if (props.complete) {
pause();
} else {
resume(); resume();
}
}); });
watch(
() => [props.loading, props.complete, props.error],
() => check('watch'),
);
</script> </script>
<template> <template>
<div class="infinite-loading" ref="target"> <div class="infinite-loading" ref="target">
<div v-if="state === 'complete'" class="infinite-loading__complete"> <div v-if="complete" class="infinite-loading__complete">
<slot name="complete"> <slot name="complete">
<span>没有更多了</span> <span>没有更多了</span>
</slot> </slot>
</div> </div>
<template v-else> <template v-else>
<div v-show="state == 'loading'" class="infinite-loading__loading"> <template v-if="error">
<div class="infinite-loading__error" @click="emit('clickError')">
<slot name="error">
<span> {{ props.errorText || '加载失败,点击重试' }} </span>
</slot>
</div>
</template>
<template v-else>
<div v-show="loading" class="infinite-loading__loading">
<slot name="loading"> <slot name="loading">
<span> 加载中... </span> <span> 加载中... </span>
</slot> </slot>
</div> </div>
<!-- 如果 isSupportedloaded 状态应该永远不会出现 --> <div v-show="!loading" class="infinite-loading__loaded" @click="check('click loaded')">
<div <slot name="loaded">
v-show="state === 'loaded' || state === ''" <span> 加载更多 </span>
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"
@click="
() => {
!$slots.error && load('click error');
}
"
>
<slot name="error" :retry="load">
<span> 加载失败点击重试 </span>
</slot> </slot>
</div> </div>
</template> </template>
</template>
</div> </div>
</template> </template>
@ -156,7 +144,7 @@ onMounted(() => {
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
min-height: 40px; min-height: 3rem;
color: #666; color: #666;
} }
.infinite-loading__loaded, .infinite-loading__loaded,

View File

@ -7,6 +7,7 @@ const router = useRouter();
const menuItems = computed(() => { const menuItems = computed(() => {
let flatArray: MenuItem[] = createGetRoutes(router)() let flatArray: MenuItem[] = createGetRoutes(router)()
.filter((route) => !route.path.includes('/:')) .filter((route) => !route.path.includes('/:'))
.filter((route) => !route.meta.hidden)
.map((route) => ({ .map((route) => ({
id: route.path, id: route.path,
label: `${(route.name as string) || route.path}`, label: `${(route.name as string) || route.path}`,

View File

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

View File

@ -1,57 +1,108 @@
<script lang="ts"> <script lang="ts">
import { toRaw } from 'vue';
const structuredClone = window.structuredClone || ((obj) => JSON.parse(JSON.stringify(obj))); const structuredClone = window.structuredClone || ((obj) => JSON.parse(JSON.stringify(obj)));
const K_INITIAL_CACHE = deepFreeze({ const K_INITIAL_STATE = deepFreeze({
page: 0,
list: [] as Record<string, never>[], 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) => let page3ShouldError = true;
Object.assign(cache, Object.fromEntries(Object.entries(newCache).map(([key, value]) => [key, toRaw(value)]))); const state = shallowReactive(structuredClone(K_INITIAL_STATE));
const clearCache = () => Object.assign(cache, structuredClone(K_INITIAL_CACHE));
// XXX: 可以直接把 list 定义在这上面???
</script> </script>
<script setup lang="ts"> <script setup lang="ts">
defineOptions({ defineOptions({
beforeRouteEnter: (to, from) => { beforeRouteEnter: (to, from) => {
if (from.name !== 'InfiniteLoadingDetail') clearCache(); // 如果来的页面不是详情页,清空缓存。 if (from.name !== 'InfiniteLoadingDetail') {
Object.assign(state, structuredClone(K_INITIAL_STATE));
}
}, },
beforeRouteLeave: (to, from) => { beforeRouteLeave: (to, from) => {
if (to.name !== 'InfiniteLoadingDetail') clearCache(); // 如果去的页面不是详情页,清空缓存。 if (to.name !== 'InfiniteLoadingDetail') {
Object.assign(state, structuredClone(K_INITIAL_STATE));
}
}, },
}); });
const refresh = () => {
let isPage2ErrorVisible = true; state.list.splice(0, state.list.length);
const lastCache = structuredClone(cache); // 要在 `loadData` 之前获取,因为 `loadData` 会修改 `cache.page`。 state.page = 0;
state.complete = false;
const list = shallowRef<Record<string, never>[]>(lastCache.list); loadMore();
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 };
}; };
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> </script>
<template> <template>
<Button label="刷新" @click="list.splice(0, list.length) && $refs.infiniteLoading?.refresh()" mb-4 /> <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>
<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 <Card
v-for="item in list" v-for="item in state.list"
:key="item.id" :key="item.id"
class="mb-[16px]" class="mb-[16px]"
@click="$router.push({ name: 'InfiniteLoadingDetail', query: { id: item.id } })" @click="$router.push({ name: 'InfiniteLoadingDetail', query: { id: item.id } })"
@ -63,13 +114,17 @@ const loadData = async (page: number) => {
<template #subtitle>id:{{ item.id }} </template> <template #subtitle>id:{{ item.id }} </template>
<template #footer>{{ item.email }}</template> <template #footer>{{ item.email }}</template>
</Card> </Card>
<div border="1 px solid red"> <UseIntersectionObserverInfiniteLoading
{{ { 'list.length': list.length } }} @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> </div>
<UseIntersectionObserverInfiniteLoading :async-load="loadData" ref="infiniteLoading"> </template>
<!-- <template #error="{ retry }">
<Button fluid @click="retry">Retry</Button>
</template> -->
</UseIntersectionObserverInfiniteLoading>
<ScrollTop /> <ScrollTop />
</template> </template>

View File

@ -39,3 +39,12 @@ export function install({ app }: { app: import('vue').App<Element> }) {
createLogGuard(router); createLogGuard(router);
Object.assign(window, { stack: createStackGuard(router) }); Object.assign(window, { stack: createStackGuard(router) });
} }
declare module 'vue-router' {
interface RouteMeta {
/**
* @description 是否在菜单中隐藏
*/
hidden?: boolean;
}
}

View File

@ -29,9 +29,11 @@
"paths": { "paths": {
"@/*": ["./src/*"] "@/*": ["./src/*"]
} }
},
// https://vue-macros.dev/volar/setup-jsdoc.html#setupjsdoc
// https://vue-macros.dev/zh-CN/guide/bundler-integration.html#volar-支持
"vueCompilerOptions": {
"plugins": ["unplugin-vue-macros/volar"]
} }
// // https://vue-macros.dev/zh-CN/guide/bundler-integration.html#typescript-支持
// "vueCompilerOptions": {
// "plugins": ["unplugin-vue-macros/volar"]
// }
} }