1
0
mirror of https://github.com/ialley-workshop-open/uni-halo.git synced 2026-11-13 22:11:42 +08:00

feat: 新增加载更多组件,完善数据加载状态管理

1.  新增uh-data-loadmore加载更多组件,适配下拉加载场景
2.  扩展DataLoadingStatus类型,新增no-network状态
3.  重构useDataLoadingStatus hooks,新增加载更多状态管理
4.  优化分类页面加载逻辑,替换旧的加载更多实现
5.  调整维护页、加载提示文案细节
6.  重构轮播详情页,统一使用数据加载状态机
7.  删除过时的useDataLoading测试文件
This commit is contained in:
小莫唐尼
2026-09-11 22:49:45 +08:00
parent f76e8a43d4
commit 9c06766f81
8 changed files with 252 additions and 292 deletions
@@ -20,7 +20,7 @@
loadingStatus: 'loading',
size: 'large',
minHeight: '80vh',
loadingText: '稍等,正在加载中哦',
loadingText: '稍等,正在加载中哦~',
errorText: '哎呀,加载失败了呢~',
emptyText: '啊偶,暂时没有数据呢~',
loadingSubText: '',
@@ -0,0 +1,15 @@
<script setup lang="ts">
import type { LoadMoreStatus } from '@/hooks/useDataLoadingStatus'
interface IProps {
text : string
status : LoadMoreStatus
}
const props = defineProps<IProps>()
</script>
<template>
<view class="w-full py-5 flex items-center justify-center gap-x-2 text-xs text-gray-400">
<wd-loading v-if="props.status==='loading'" size="32rpx" color="#D7F94C"></wd-loading> {{ props.text }}
</view>
</template>
-84
View File
@@ -1,84 +0,0 @@
import { mount } from '@vue/test-utils'
import { describe, expect, it, vi } from 'vitest'
import { defineComponent, h } from 'vue'
import { useDataLoading } from './useDataLoading'
/**
* 在 Vue 应用上下文中运行 composable。
* composable 的 ref/computed 只能在 setup() 内使用,
* withSetup 通过挂载一个临时组件来提供这个上下文。
*/
function withSetup<T>(composableFn: () => T): T {
let result!: T
const Comp = defineComponent({
setup() {
result = composableFn()
return () => h('div')
},
})
const wrapper = mount(Comp)
wrapper.unmount()
return result
}
describe('useDataLoading', () => {
it('初始状态:status=loading, data=undefined', () => {
const fetcher = vi.fn().mockResolvedValue('data')
const { status, data } = withSetup(() => useDataLoading(fetcher))
expect(status.value).toBe('loading')
expect(data.value).toBeUndefined()
})
it('run 成功:status 从 loading 流转到 success,data 更新为返回值并触发 onSuccess', async () => {
const fetcher = vi.fn().mockResolvedValue('result')
const onSuccess = vi.fn()
const { status, data, run } = withSetup(() => useDataLoading(fetcher, { onSuccess }))
const promise = run()
expect(status.value).toBe('loading')
await promise
expect(status.value).toBe('success')
expect(data.value).toBe('result')
expect(onSuccess).toHaveBeenCalledWith('result')
})
it('run 返回空数组:status 流转到 empty', async () => {
const fetcher = vi.fn().mockResolvedValue([])
const { status, run } = withSetup(() => useDataLoading(fetcher))
await run()
expect(status.value).toBe('empty')
})
it('isEmpty 自定义判空:返回 true 时 status 为 empty', async () => {
const fetcher = vi.fn(async (): Promise<{ total: number, items: number[] }> => ({ total: 0, items: [1] }))
const { status, run } = withSetup(() => useDataLoading(fetcher, { isEmpty: data => data.total === 0 }))
await run()
expect(status.value).toBe('empty')
})
it('run 失败:不向外抛出异常,status 流转到 error 并触发 onError', async () => {
const err = new Error('network error')
const onError = vi.fn()
const fetcher = vi.fn().mockRejectedValue(err)
const { status, data, run } = withSetup(() => useDataLoading(fetcher, { onError }))
await expect(run()).resolves.toBeUndefined()
expect(status.value).toBe('error')
expect(data.value).toBeUndefined()
expect(onError).toHaveBeenCalledWith(err)
})
it('带参数 run:参数透传给 fetcher', async () => {
const fetcher = vi.fn(async (name: string) => `hi ${name}`)
const { data, run } = withSetup(() => useDataLoading(fetcher))
await run('world')
expect(fetcher).toHaveBeenCalledWith('world')
expect(data.value).toBe('hi world')
})
})
+1 -1
View File
@@ -2,7 +2,7 @@ import type { Ref } from 'vue'
import { ref } from 'vue'
/** 数据加载四态(取值与旧 DataLoadingStatusEnum 一致,二者可互相兼容) */
export type DataLoadingStatus = 'loading' | 'error' | 'empty' | 'success'
export type DataLoadingStatus = 'loading' | 'error' | 'empty' | 'success' |'no-network'
export interface IUseDataLoadingOptions<T> {
/** 自定义判空;默认:数组看长度、对象看键数、空值视为空 */
+76 -21
View File
@@ -1,27 +1,82 @@
import type { DataLoadingStatus } from './useDataLoading'
export const DataLoadingStatusEnum = {
Loading: 'loading',
Error: 'error',
Empty: 'empty',
Success: 'success',
NoNetwork: 'noNetwork',
} as const
Loading: 'loading',
Error: 'error',
Empty: 'empty',
Success: 'success',
NoNetwork: 'noNetwork'
} as const;
export function useDataLoadingStatus(status?: DataLoadingStatus) {
const loadingStatus = ref<DataLoadingStatus>(status ?? DataLoadingStatusEnum.Loading)
export type DataLoadingStatus = (typeof DataLoadingStatusEnum)[keyof typeof DataLoadingStatusEnum];
function resetLoadingStatus() {
loadingStatus.value = DataLoadingStatusEnum.Loading
}
const LoadMoreStatusText = {
loadMore: '哎嘿,往下还有数据哦~',
loading: '稍等,正在加载中哦~',
noMore: '呜呜,没有更多数据了~',
error: '呜呜,加载失败了哦~',
noNetwork: '呜呜,网络好像有点问题哦~'
} as const;
function updateLoadingStatus(newStatus: DataLoadingStatus) {
loadingStatus.value = newStatus
}
export type LoadMoreStatus = keyof typeof LoadMoreStatusText
return {
loadingStatus,
resetLoadingStatus,
updateLoadingStatus,
}
export interface LoadMoreStatusOption {
// 是否激活加载
active?: boolean;
status?: LoadMoreStatus;
text?: string;
hasNext?: boolean;
}
export function useDataLoadingStatus(defaultStatus?: DataLoadingStatus) {
const loadingStatus = ref<DataLoadingStatus>(defaultStatus ?? DataLoadingStatusEnum.Loading);
const _loadMoreStatus = ref<LoadMoreStatus>({
active: false,
hasNext: false,
status: 'loadMore',
text: ''
});
const loadMoreStatus = computed(() => {
const result = {
..._loadMoreStatus.value
};
if (!_loadMoreStatus.value.text) {
result.text = LoadMoreStatusText[_loadMoreStatus.value.status];
}
console.log('会触发吗?', _loadMoreStatus.value);
console.log('会触发吗 result', result);
return result;
});
function resetLoadMoreStatus() {
_loadMoreStatus.value.active = false;
_loadMoreStatus.value.hasNext = false;
_loadMoreStatus.value.status = 'loadMore';
_loadMoreStatus.value.text = '';
}
function resetLoadingStatus() {
loadingStatus.value = DataLoadingStatusEnum.Loading;
resetLoadMoreStatus();
}
function updateLoadingStatus(status: DataLoadingStatus) {
loadingStatus.value = status;
}
function updateLoadMoreStatus(status: LoadMoreStatusOption) {
_loadMoreStatus.value.active = status.active;
_loadMoreStatus.value.status = status.status;
_loadMoreStatus.value.hasNext = status.hasNext;
_loadMoreStatus.value.text = status.text;
}
return {
loadingStatus,
loadMoreStatus,
resetLoadingStatus,
resetLoadMoreStatus,
updateLoadingStatus,
updateLoadMoreStatus
};
}
+110 -140
View File
@@ -2,7 +2,7 @@
/**
* 轮播详情页(自定义 Banner 条目点击后进入)
* 通过公开详情接口(getBannerDetail)拉取 content 富文本与外链,类文章详情页
* 外链平台差异(条件编译):非 APP-PLUS(小程序/H5)提供复制+显示链接,APP-PLUS 提供访问按钮(web-view)
* 外链平台差异(条件编译):非 APP-PLUS(小程序/H5)提供复制链接,APP-PLUS 提供访问按钮(web-view)
*/
import { computed, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
@@ -10,176 +10,146 @@ import { getBannerDetail } from '@/api/uni-halo'
import { checkAvatarUrl, checkThumbnailUrl } from '@/utils/url'
import { formatTime } from '@/utils/formatTime'
import { copyToClipboard } from '@/utils/restrictRead'
import { sleep } from '@/utils/common'
import { markdownConfig } from '@/config/markdown'
import { DataLoadingStatusEnum, useDataLoadingStatus } from '@/hooks/useDataLoadingStatus'
import type { IBannerPublicDetail } from '@/api/types/uni-halo'
definePage({
style: {
navigationBarTitleText: '轮播详情',
},
style: {
navigationBarTitleText: '轮播详情',
navigationStyle: 'custom',
},
})
const loading = ref<'loading' | 'success' | 'error'>('loading')
const { loadingStatus, updateLoadingStatus } = useDataLoadingStatus()
const name = ref('')
const detail = ref<IBannerPublicDetail | null>(null)
const linkCopied = ref(false)
async function handleGetData(name: string) {
loading.value = 'loading'
try {
const res = await getBannerDetail(name)
detail.value = res.data || null
if (detail.value?.title) {
uni.setNavigationBarTitle({ title: detail.value.title })
}
loading.value = 'success'
}
catch (err) {
console.error('获取轮播详情失败', err)
loading.value = 'error'
}
}
function handleRetry() {
const name = detail.value?.name || ''
if (name) {
handleGetData(name)
}
}
onLoad((options) => {
const name = options?.name
if (name) {
handleGetData(name)
}
else {
loading.value = 'error'
}
})
/** 封面图:无封面时回退默认缩略图 */
const coverUrl = computed(() => checkThumbnailUrl(detail.value?.cover, true))
const authorName = computed(() => detail.value?.authorName || '')
const authorAvatar = computed(() =>
detail.value?.authorAvatar ? checkAvatarUrl(detail.value.authorAvatar) : '',
detail.value?.authorAvatar ? checkAvatarUrl(detail.value.authorAvatar) : '',
)
const dateText = computed(() => {
if (!detail.value?.date) {
return ''
}
const d = new Date(detail.value.date)
if (Number.isNaN(d.getTime())) {
return ''
}
return formatTime({ d: detail.value.date, f: 'yyyy-MM-dd' })
if (!detail.value?.date) {
return ''
}
const d = new Date(detail.value.date)
if (Number.isNaN(d.getTime())) {
return ''
}
return formatTime({ d: detail.value.date, f: 'yyyy-MM-dd' })
})
const content = computed(() => detail.value?.content || '')
/** 外链存在即展示底部操作(复制/访问) */
const hasLink = computed(() => !!detail.value?.link)
/** 加载轮播详情(状态机;404/无数据 → 空态,其余错误 → error 态,可重试) */
async function loadDetail() {
updateLoadingStatus(DataLoadingStatusEnum.Loading)
if (!name.value) {
updateLoadingStatus(DataLoadingStatusEnum.Empty)
return
}
try {
const res = await getBannerDetail(name.value)
detail.value = res.data || null
await sleep(600)
updateLoadingStatus(detail.value ? DataLoadingStatusEnum.Success : DataLoadingStatusEnum.Empty)
}
catch (err) {
console.error('轮播详情加载失败', err)
const code = (err as { code ?: number }).code
updateLoadingStatus(code === 404 ? DataLoadingStatusEnum.Empty : DataLoadingStatusEnum.Error)
}
}
onLoad((options) => {
name.value = options?.name || ''
loadDetail()
})
/** 非 APP-PLUS:复制链接 */
function handleCopyLink() {
if (!detail.value?.link) {
return
}
copyToClipboard(detail.value.link, '链接已复制')
linkCopied.value = true
setTimeout(() => {
linkCopied.value = false
}, 1500)
if (!detail.value?.link) {
return
}
copyToClipboard(detail.value.link, '链接已复制')
linkCopied.value = true
setTimeout(() => {
linkCopied.value = false
}, 1500)
}
/** APP-PLUS:打开内置 web-view 访问外链 */
function handleOpenLink() {
if (!detail.value?.link) {
return
}
uni.navigateTo({
url: `/pages-blog/website/website?data=${JSON.stringify({
title: detail.value.title || '查看链接',
url: encodeURIComponent(detail.value.link),
})}`,
})
if (!detail.value?.link) {
return
}
uni.navigateTo({
url: `/pages-blog/website/website?data=${JSON.stringify({
title: detail.value.title || '查看链接',
url: encodeURIComponent(detail.value.link),
})}`,
})
}
</script>
<template>
<view class="app-page">
<!-- 加载/错误占位 -->
<view v-if="loading !== 'success'">
<uh-data-loading :loading-status="loading" @refresh="handleRetry" />
</view>
<view class="box-border min-h-screen w-screen bg-page pb-safe">
<!-- 自定义导航 -->
<uh-navbar default-title="轮播详情" title-color="text-gray-900" :scroll-title="detail?.title" />
<!-- 详情内容 -->
<view v-else-if="detail" class="pb-8">
<!-- 封面图 -->
<image v-if="coverUrl" :src="coverUrl" class="h-[420rpx] w-full" mode="aspectFill" />
<!-- 加载/错误/空态(状态机) -->
<uh-data-loading v-if="loadingStatus !== 'success'" :loading-status="loadingStatus" min-height="75vh"
error-text="轮播详情加载失败" empty-text="轮播图不存在或已下线" empty-sub-text="" @refresh="loadDetail" />
<view class="px-4">
<!-- 标题 -->
<view class="mt-6 text-[34rpx] text-[#303133] font-bold leading-snug">
{{ detail.title }}
</view>
<!-- 正文 -->
<view v-else-if="detail" class="box-border p-4">
<image v-if="coverUrl" class="mb-5 h-[320rpx] w-full rounded-xl" :src="coverUrl" mode="aspectFill" />
<!-- 作者/日期信息 -->
<view v-if="authorName || dateText" class="mt-3 flex items-center gap-2">
<image
v-if="authorAvatar"
:src="authorAvatar"
class="h-[44rpx] w-[44rpx] rounded-full"
mode="aspectFill"
/>
<text class="text-[24rpx] text-[#909399]">{{ authorName }}</text>
<text v-if="dateText" class="text-[22rpx] text-[#c0c4cc]">{{ dateText }}</text>
</view>
<view class="text-[36rpx] font-bold leading-snug text-gray-900">
{{ detail.title }}
</view>
<!-- 富文本内容 -->
<view v-if="detail.content" class="mt-6 border-t border-[#f0f0f0] pt-6">
<mp-html :content="detail.content" />
</view>
<!-- 作者/日期信息 -->
<view v-if="authorName || dateText" class="mt-3 flex items-center gap-2">
<image v-if="authorAvatar" :src="authorAvatar" class="h-[44rpx] w-[44rpx] rounded-full"
mode="aspectFill" />
<text class="text-[24rpx] text-gray-500">{{ authorName }}</text>
<text v-if="dateText" class="text-[22rpx] text-gray-500">{{ dateText }}</text>
</view>
<!-- 外链(平台差异,条件编译) -->
<view v-if="detail.link" class="link-card mt-8 rounded-xl bg-[#f7f7f9] p-4">
<view class="mb-3 text-[24rpx] text-[#909399]">
相关链接
</view>
<text class="link-text block break-all text-[26rpx] text-[#606266] leading-relaxed">
{{ detail.link }}
</text>
<!-- #ifndef APP-PLUS -->
<!-- 非 App 端(小程序/H5):复制 + 提示已复制 -->
<view
class="link-btn mt-3 inline-flex items-center rounded-lg px-6 py-2 text-[24rpx] text-white"
:class="linkCopied ? 'link-btn-copied' : ''"
@click="handleCopyLink"
>
{{ linkCopied ? '已复制' : '复制链接' }}
</view>
<!-- #endif -->
<!-- #ifdef APP-PLUS -->
<!-- App 端:访问按钮(内置 web-view) -->
<view class="link-btn mt-3 inline-flex items-center rounded-lg px-6 py-2 text-[24rpx] text-white" @click="handleOpenLink">
访问链接
</view>
<!-- #endif -->
</view>
</view>
</view>
</view>
<!-- 富文本内容 -->
<view v-if="content" class="box-border w-full mt-2 pt-4 pb-6">
<mp-html :content="content" lazy-load :domain="markdownConfig.domain ?? ''" scroll-table selectable
:tag-style="markdownConfig.tagStyle" :container-style="markdownConfig.containStyle"
:show-line-number="false" copy-by-long-press />
</view>
<!-- 外链(平台差异,条件编译):非 APP 复制 / APP 访问 -->
<view v-if="hasLink" class="fixed left-0 right-0 bottom-0 pb-safe px-4 box-border">
<view class="w-full h-full uh-global-card-glass border rounded-full mb-4">
<!-- #ifndef APP-PLUS -->
<uh-button custom-class="w-full !rounded-full py-2.5 font-medium" @click="handleCopyLink">
{{ linkCopied ? '已复制' : '复制链接' }}
</uh-button>
<!-- #endif -->
<!-- #ifdef APP-PLUS -->
<uh-button custom-class="w-full !rounded-full py-2.5 font-medium" @click="handleOpenLink">
访问链接
</uh-button>
<!-- #endif -->
</view>
</view>
</view>
</view>
</template>
<style scoped lang="scss">
.app-page {
min-height: 100vh;
background: #fff;
}
.link-text {
word-break: break-all;
}
.link-btn {
background: #2563eb;
&.link-btn-copied {
background: #10b981;
}
}
</style>
+1 -1
View File
@@ -329,7 +329,7 @@
<text v-for="(line, index) in noticeLines" :key="index" class="block">{{ line }}</text>
</template>
<template v-else>
<text>为了给你带来更好的体验,站点正在维护升级中</text>
<text>为了给你带来更好的体验,正在维护升级中</text>
<text class="block">
别担心,我们很快就回来!
</text>
+46 -42
View File
@@ -25,23 +25,18 @@
const categoryConfig = computed(() => haloConfigs.value.pageConfig?.categoryConfig)
/* ---------------- 状态 ---------------- */
const { loadingStatus, updateLoadingStatus } = useDataLoadingStatus()
const { loadingStatus, loadMoreStatus, updateLoadingStatus, updateLoadMoreStatus, resetLoadingStatus, resetLoadMoreStatus } = useDataLoadingStatus()
const queryParams = ref({
size: 20,
size: 3,
page: 1,
fieldSelector: ['spec.hideFromList=false'],
})
const hasNext = ref(false)
const dataList = ref<ICategory[]>([])
const isLoadMore = ref(false)
const loadMoreText = ref(t('common.loading'))
function handleResetInit() {
dataList.value = []
queryParams.value.page = 1
hasNext.value = false
isLoadMore.value = false
loadMoreText.value = t('common.loading')
resetLoadingStatus()
}
function handleInitPage() {
@@ -51,11 +46,12 @@
/* ---------------- 数据加载 ---------------- */
async function handleGetData() {
updateLoadingStatus(DataLoadingStatusEnum.Loading)
// 增加延迟,提升用户体验
await sleep(800)
// 审核模式:直接使用审核配置分类快照(categoryDetails)映射 ICategory,免请求
if (!loadMoreStatus.value.active) {
updateLoadingStatus(DataLoadingStatusEnum.Loading)
}
// 审核模式
if (calcAuditModeEnabled.value) {
resetLoadMoreStatus()
const auditCategoryDetails = appConfigStore.auditData.categoryDetails || []
try {
dataList.value = auditCategoryDetails.map(item => ({
@@ -68,51 +64,60 @@
},
postCount: item.postCount ?? 0,
} as ICategory))
await sleep(600)
updateLoadingStatus(dataList.value.length === 0 ? DataLoadingStatusEnum.Empty : DataLoadingStatusEnum.Success)
loadMoreText.value = t('common.noMore')
uni.hideLoading()
updateLoadMoreStatus({
active: false,
status: 'noMore',
hasNext: false
})
uni.stopPullDownRefresh()
}
catch (err) {
console.error(err)
updateLoadingStatus(DataLoadingStatusEnum.Error)
loadMoreText.value = t('common.loadFailed')
}
return
}
if (!isLoadMore.value) {
updateLoadingStatus(DataLoadingStatusEnum.Loading)
}
loadMoreText.value = t('common.loading')
try {
const res = await getCategoryList({ ...queryParams.value })
loadMoreText.value = res.data.hasNext ? t('common.loadMore') : t('common.noMore')
hasNext.value = res.data.hasNext
const tempItems = res.data.items.map(item => ({
...item,
postCount: item.postCount ?? 0,
spec: { ...item.spec, cover: checkThumbnailUrl(item.spec.cover, true) },
}))
dataList.value = isLoadMore.value
dataList.value = loadMoreStatus.value.active
? dataList.value.concat(tempItems)
: tempItems
updateLoadingStatus(dataList.value.length === 0 ? DataLoadingStatusEnum.Empty : DataLoadingStatusEnum.Success)
if (!loadMoreStatus.value.active) {
await sleep(600)
updateLoadingStatus(dataList.value.length === 0 ? DataLoadingStatusEnum.Empty : DataLoadingStatusEnum.Success)
}
updateLoadMoreStatus({
active: false,
status: res.data.hasNext ? 'loadMore' : 'noMore',
hasNext: res.data.hasNext
})
}
catch (err) {
console.error(err)
updateLoadingStatus(DataLoadingStatusEnum.Error)
loadMoreText.value = t('common.loadFailed')
if (loadMoreStatus.value.active) {
updateLoadMoreStatus({
active: false,
status: 'error',
})
}
else {
updateLoadingStatus(DataLoadingStatusEnum.Error)
}
}
finally {
setTimeout(() => {
uni.hideLoading()
uni.stopPullDownRefresh()
}, 500)
uni.stopPullDownRefresh()
}
}
@@ -135,18 +140,19 @@
})
onReachBottom(() => {
if (calcAuditModeEnabled.value) {
uni.showToast({ icon: 'none', title: t('common.noMoreData') })
return
// 如果正在请求,需要阻止继续发起请求
if (loadMoreStatus.value.active && loadMoreStatus.value.loading) {
return;
}
if (hasNext.value) {
// 有更多数据时,继续加载数据
if (loadMoreStatus.value.hasNext) {
queryParams.value.page += 1
isLoadMore.value = true
updateLoadMoreStatus({
active: true,
status: 'loading'
})
handleGetData()
}
else {
uni.showToast({ icon: 'none', title: t('common.noMoreData') })
}
})
</script>
@@ -174,9 +180,7 @@
</view>
</view>
</view>
<view class="w-full py-5 text-center text-xs text-gray-400">
{{ loadMoreText }}
</view>
<uh-data-loadmore :status="loadMoreStatus.status" :text="loadMoreStatus.text"></uh-data-loadmore>
</block>
</view>
</template>