feat: 添加无限加载组件和示例页面
This commit is contained in:
86
src/components/UseIntersectionObserverInfiniteLoading.vue
Normal file
86
src/components/UseIntersectionObserverInfiniteLoading.vue
Normal file
@ -0,0 +1,86 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
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
|
||||||
|
);
|
||||||
|
}
|
||||||
|
</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 }>;
|
||||||
|
}>();
|
||||||
|
|
||||||
|
const load = async () => {
|
||||||
|
if (state.value === 'loading') return;
|
||||||
|
|
||||||
|
state.value = 'loading';
|
||||||
|
try {
|
||||||
|
const { hasMore } = await props.asyncLoad();
|
||||||
|
state.value = hasMore ? 'loaded' : 'complete';
|
||||||
|
if (hasMore) {
|
||||||
|
await nextTick();
|
||||||
|
if (checkIsVisible(target.value!)) {
|
||||||
|
load();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!hasMore) {
|
||||||
|
pause(); // TODO: 下拉刷新后,怎么恢复? maybe @register
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
state.value = 'error';
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const { pause /* , resume, isSupported, isActive */ } = useIntersectionObserver(
|
||||||
|
target,
|
||||||
|
([entry]) => {
|
||||||
|
if (entry?.isIntersecting) {
|
||||||
|
load();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// 数值形式(单个值):表示目标元素可见部分与整个目标元素的比例。例如:threshold: 0.5
|
||||||
|
// 目标元素可见比例达到 50% 时触发回调。
|
||||||
|
// 数组形式(多个值):表示多个可见比例触发点。例如:threshold: [0, 0.25, 0.5, 0.75, 1.0]。
|
||||||
|
// 在目标元素可见部分从 0% 增加到 100% 时,每达到一个阈值都会触发回调。
|
||||||
|
threshold: 0,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="infinite-loading" ref="target">
|
||||||
|
<slot v-if="state === 'complete'" name="complete">
|
||||||
|
<span>没有更多了</span>
|
||||||
|
</slot>
|
||||||
|
<template v-else>
|
||||||
|
<div v-show="state == 'loading'">
|
||||||
|
<slot name="loading">
|
||||||
|
<span> 加载中... </span>
|
||||||
|
</slot>
|
||||||
|
</div>
|
||||||
|
<slot v-if="state === 'error'" name="error">
|
||||||
|
<div>
|
||||||
|
<span> 加载失败 </span>
|
||||||
|
<button @click="load">重试</button>
|
||||||
|
</div>
|
||||||
|
</slot>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</template>
|
32
src/pages/InfiniteLoading.page.vue
Normal file
32
src/pages/InfiniteLoading.page.vue
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
let showDebugError = true;
|
||||||
|
const DEBUG_MAX_PAGE = 5;
|
||||||
|
|
||||||
|
let page = 0;
|
||||||
|
const list = ref<Record<string, never>[]>([]);
|
||||||
|
const loadData = async () => {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 1250));
|
||||||
|
if (page === 1 && showDebugError) {
|
||||||
|
showDebugError = false;
|
||||||
|
throw new Error('Failed to load comments');
|
||||||
|
}
|
||||||
|
// FIXME: 如果接口出错了要把 page 恢复
|
||||||
|
const response = await fetch(`https://jsonplaceholder.typicode.com/comments?_page=${++page}&_limit=1`);
|
||||||
|
const data = await response.json();
|
||||||
|
list.value.push(...data);
|
||||||
|
return { hasMore: page < DEBUG_MAX_PAGE };
|
||||||
|
};
|
||||||
|
</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>
|
||||||
|
<UseIntersectionObserverInfiniteLoading :async-load="loadData" />
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped></style>
|
@ -2,39 +2,87 @@
|
|||||||
import { useIntersectionObserver } from '@vueuse/core';
|
import { useIntersectionObserver } from '@vueuse/core';
|
||||||
import { ref } from 'vue';
|
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 loading = ref(false);
|
||||||
const list = ref<string[]>([]);
|
const page = ref(0);
|
||||||
|
const pageSize = 1;
|
||||||
|
|
||||||
const loadMore = async () => {
|
const loadMore = async () => {
|
||||||
|
if (loading.value) return;
|
||||||
|
|
||||||
loading.value = true;
|
loading.value = true;
|
||||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
try {
|
||||||
const items = Array.from({ length: 5 }, (_, i) => `Item ${list.value.length + i + 1}`);
|
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||||
list.value.push(...items);
|
const response = await fetch(
|
||||||
loading.value = false;
|
`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 target = ref(null);
|
||||||
const isVisible = ref(false);
|
const isVisible = ref(false);
|
||||||
|
|
||||||
const { isActive, pause, resume, isSupported } = useIntersectionObserver([target], ([entry]) => {
|
const { isActive, pause, resume, isSupported } = useIntersectionObserver(
|
||||||
isVisible.value = entry?.isIntersecting || false;
|
target,
|
||||||
});
|
([entry]) => {
|
||||||
|
isVisible.value = entry?.isIntersecting || false;
|
||||||
|
if (entry?.isIntersecting) {
|
||||||
|
loadMore();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
// { threshold: 0.1 },
|
||||||
|
);
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<Card v-for="item in list" :key="item" class="mb-[16px]">
|
<Card v-for="item in list" :key="item.id" class="mb-[16px]">
|
||||||
<template #title>{{ item }}</template>
|
<template #title>{{ item.name }}</template>
|
||||||
|
<template #content>
|
||||||
|
<p class="text-gray-600">{{ item.email }}</p>
|
||||||
|
<p class="mt-[8px]">{{ item.body }}</p>
|
||||||
|
</template>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
<div ref="target" class="border-[8px] border-blue-500 p-[16px] bg-white dark:bg-gray-800 dark:border-gray-700">
|
<div ref="target" class="border-[8px] border-blue-500 p-[16px]">
|
||||||
<Button label="Load more" :loading="loading" fluid @click="loadMore" />
|
<Button label="Load more" :loading="loading" fluid @click="loadMore" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<ScrollTop />
|
<ScrollTop />
|
||||||
<div
|
<div class="border-[1px] border-blue-500 fixed top-16 right-16 p-[4px] bg-white" flex="~ col" items-end>
|
||||||
class="border-[1px] border-blue-500 fixed top-16 right-16 p-[4px] bg-white dark:bg-gray-800 dark:border-gray-700"
|
|
||||||
flex="~ col"
|
|
||||||
items-end
|
|
||||||
>
|
|
||||||
<label class="checkbox">
|
<label class="checkbox">
|
||||||
<span mr="[8px]">isSupported: {{ isSupported }}</span>
|
<span mr="[8px]">isSupported: {{ isSupported }}</span>
|
||||||
<input
|
<input
|
||||||
@ -47,7 +95,7 @@ const { isActive, pause, resume, isSupported } = useIntersectionObserver([target
|
|||||||
</label>
|
</label>
|
||||||
<div>
|
<div>
|
||||||
Element
|
Element
|
||||||
<span class="font-bold" :class="isVisible ? 'text-blue-500' : 'text-orange-400 dark:text-orange-300'">
|
<span class="font-bold" :class="isVisible ? 'text-blue-500' : 'text-orange-400'">
|
||||||
{{ isVisible ? 'inside' : 'outside' }}
|
{{ isVisible ? 'inside' : 'outside' }}
|
||||||
</span>
|
</span>
|
||||||
the viewport
|
the viewport
|
||||||
|
1
typed-router.d.ts
vendored
1
typed-router.d.ts
vendored
@ -25,6 +25,7 @@ declare module 'vue-router/auto-routes' {
|
|||||||
'Api': RouteRecordInfo<'Api', '/api', Record<never, never>, Record<never, never>>,
|
'Api': RouteRecordInfo<'Api', '/api', Record<never, never>, Record<never, never>>,
|
||||||
'DataLoadersId': RouteRecordInfo<'DataLoadersId', '/data-loaders/:id', { id: ParamValue<true> }, { id: ParamValue<false> }>,
|
'DataLoadersId': RouteRecordInfo<'DataLoadersId', '/data-loaders/:id', { id: ParamValue<true> }, { id: ParamValue<false> }>,
|
||||||
'IndexPage': RouteRecordInfo<'IndexPage', '/index-page', Record<never, never>, Record<never, never>>,
|
'IndexPage': RouteRecordInfo<'IndexPage', '/index-page', Record<never, never>, Record<never, never>>,
|
||||||
|
'InfiniteLoading': RouteRecordInfo<'InfiniteLoading', '/InfiniteLoading', Record<never, never>, Record<never, never>>,
|
||||||
'MdPage': RouteRecordInfo<'MdPage', '/md-page', 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>>,
|
'SomePage': RouteRecordInfo<'SomePage', '/some-page', Record<never, never>, Record<never, never>>,
|
||||||
'TsEnumUtil': RouteRecordInfo<'TsEnumUtil', '/ts-enum-util', Record<never, never>, Record<never, never>>,
|
'TsEnumUtil': RouteRecordInfo<'TsEnumUtil', '/ts-enum-util', Record<never, never>, Record<never, never>>,
|
||||||
|
Reference in New Issue
Block a user