🎯 目标
在加载失败、数据为空、权限限制等场景下,用统一风格的空状态组件 EmptyView
提升用户体验。
本组件具备以下能力:
-
支持多种状态类型:空数据、加载失败、无权限、无网络
-
图文可自定义
-
可配置操作按钮(如“刷新”、“去设置”、“重新登录”等)
-
默认样式统一、适配主流页面空态需求
🧱 状态类型定义
状态类型 | 标识值(type) | 默认图 | 默认文字 | 默认按钮 |
---|---|---|---|---|
无数据 | 'empty' | 📦 | 暂无内容 | '刷新' |
加载失败 | 'error' | ❌ | 加载失败,请重试 | '重试' |
无网络 | 'network' | 📡 | 网络异常,请检查连接 | '设置网络' |
无权限 | 'forbidden' | 🚫 | 当前无访问权限 | '重新登录' |
🧰 组件实现:EmptyView.ets
@Component
export struct EmptyView {
@Prop type: 'empty' | 'error' | 'network' | 'forbidden' = 'empty'
@Prop image: ResourceStr | null = null
@Prop text: string | null = null
@Prop buttonText: string | null = null
@Prop onAction: () => void = () => {}
build() {
const config = {
empty: {
image: $r('app.media.icon_empty'),
text: '暂无数据',
button: '刷新'
},
error: {
image: $r('app.media.icon_error'),
text: '加载失败,请稍后重试',
button: '重试'
},
network: {
image: $r('app.media.icon_network'),
text: '网络异常,请检查设置',
button: '设置网络'
},
forbidden: {
image: $r('app.media.icon_forbidden'),
text: '当前无权限访问',
button: '重新登录'
}
}
const cur = config[this.type]
Column({ space: 12 }) {
Image(this.image ?? cur.image).width(120).height(120)
Text(this.text ?? cur.text)
.fontSize(14)
.fontColor('#888')
Button(this.buttonText ?? cur.button)
.type(ButtonType.Normal)
.onClick(() => this.onAction())
}
.alignItems(HorizontalAlign.Center)
.justifyContent(FlexAlign.Center)
.height('100%')
}
}
📦 使用示例
@Entry
@Component
struct DemoEmpty {
@State status: 'empty' | 'error' | 'network' | 'forbidden' = 'empty'
build() {
EmptyView({
type: this.status,
onAction: () => {
console.info('执行刷新或跳转操作')
this.status = 'empty'
}
})
}
}
✨ 可扩展能力建议
功能 | 说明 |
---|---|
自定义插槽 | 支持插入图片/按钮/描述内容 |
动画支持 | 图标可替换为 Lottie/VAP 动画 |
状态复用封装 | 空态类型与错误码自动绑定 |
联动接口状态 | 配合接口封装中自动切换空态/失败图 |
📘 下一篇预告
第6篇:【HarmonyOS 5.0.0 或以上】构建分页加载组件 PageWrapper:集成刷新 / 空态 / 加载中一体封装