diff --git a/src/hooks/useScroll.ts b/src/hooks/useScroll.ts new file mode 100644 index 0000000..1563223 --- /dev/null +++ b/src/hooks/useScroll.ts @@ -0,0 +1,74 @@ +import type { Ref } from 'vue' +import { onMounted, ref } from 'vue' + +interface UseScrollOptions { + fetchData: (page: number, pageSize: number) => Promise + pageSize?: number +} + +interface UseScrollReturn { + list: Ref + loading: Ref + finished: Ref + error: Ref + refresh: () => Promise + loadMore: () => Promise +} + +export function useScroll({ + fetchData, + pageSize = 10, +}: UseScrollOptions): UseScrollReturn { + const list = ref([]) as Ref + const loading = ref(false) + const finished = ref(false) + const error = ref(null) + const page = ref(1) + + const loadData = async () => { + if (loading.value || finished.value) + return + + loading.value = true + error.value = null + + try { + const data = await fetchData(page.value, pageSize) + if (data.length < pageSize) { + finished.value = true + } + list.value.push(...data) + page.value++ + } + catch (err) { + error.value = err + } + finally { + loading.value = false + } + } + + const refresh = async () => { + page.value = 1 + finished.value = false + list.value = [] + await loadData() + } + + const loadMore = async () => { + await loadData() + } + + onMounted(() => { + refresh() + }) + + return { + list, + loading, + finished, + error, + refresh, + loadMore, + } +} diff --git a/src/pages/about/about.vue b/src/pages/about/about.vue index b25c6a1..ab82666 100644 --- a/src/pages/about/about.vue +++ b/src/pages/about/about.vue @@ -46,6 +46,11 @@ function gotoTabbar() { url: '/pages/index/index', }) } +function gotoScroll() { + uni.navigateTo({ + url: '/pages/demo/scroll', + }) +} // #region setTabbarBadge function setTabbarBadge() { tabbarStore.setTabbarItemBadge(1, 100) @@ -116,6 +121,11 @@ onShow(() => { + + +