HarmonyOSBaseLibs/src/main/ets/view/RefreshView.ets

87 行
2.8 KiB
Plaintext

2024-10-22 19:36:59 +08:00
import { ToolsHelper } from '../utils/ToolsHelper'
@Component
export struct RefreshView {
2024-10-23 16:03:00 +08:00
@Link isLoading: boolean
@Prop data: Array<ESObject>
@Require keyGenerator?: (item: ESObject, index: number) => string
init: boolean = true
pageSize: number = 10
onLoadMore?: (pageNum: number) => void
2024-10-23 16:03:00 +08:00
onRefresh?: () => void
private startY: number = 0
private endY: number = 0
private lastNum: number = 0
private _openMore: boolean = false
private _oTime: number = 0
2024-10-23 10:25:27 +08:00
aboutToAppear(): void {
if (this.init) {
this.onRefresh && this.onRefresh()
}
2024-10-23 10:25:27 +08:00
}
2024-10-22 19:36:59 +08:00
// 使用父组件@Builder装饰的方法初始化子组件@BuilderParam
2024-10-23 16:03:00 +08:00
@BuilderParam customBuilderParam: (item: ESObject, index: number) => void
2024-10-22 19:36:59 +08:00
build() {
Refresh({ refreshing: $$this.isLoading }) {
2024-10-23 16:03:00 +08:00
if (this.data && this.data.length > 0) {
List() {
ForEach(this.data ?? [], (item: ESObject, index: number) => {
ListItem() {
this.customBuilderParam(item, index)
}
}, (item: ESObject, index: number) => this.keyGenerator!(item, index))
2024-10-23 16:03:00 +08:00
}
.onTouch((event: TouchEvent) => {
const e1 = event.touches[0]
switch (event.type) {
case TouchType.Down:
this._openMore = this.data && this.lastNum >= this.data.length && !this.isLoading
this.startY = e1.y
break
case TouchType.Up:
this.endY = e1.y
if (this.endY - this.startY < -100 && this._openMore) {
const v = this.data && (this.data.length % this.pageSize) === 0
if (v) {
const cTime = new Date().getTime()
// 2024.11.21 测试觉得刷新太多了,暂时改为1秒5间隔
if (cTime - this._oTime > 1500) {
this.onLoadMore && this.onLoadMore(Math.floor(this.data.length / this.pageSize))
this._oTime = cTime
}
} else {
this.onLoadMore && ToolsHelper.showMessage('没有更多数据了')
}
2024-10-23 16:03:00 +08:00
}
break
2024-10-22 19:36:59 +08:00
}
2024-10-23 16:03:00 +08:00
})
.onScrollIndex((first: number, last: number) => {
this.lastNum = last + 1
2024-10-23 16:03:00 +08:00
})
.width('100%')
.height('100%')
.alignListItem(ListItemAlign.Center)
.scrollBar(BarState.Off)
} else {
Text('暂无数据')
.width('100%')
.height('100%')
.textAlign(TextAlign.Center)
2024-10-22 19:36:59 +08:00
}
2024-10-23 16:03:00 +08:00
}
.width('100%')
.layoutWeight(1)
2024-10-22 19:36:59 +08:00
.onStateChange((refreshStatus: RefreshStatus) => {
// ToolsHelper.log('Refresh onStatueChange state is ' + refreshStatus)
2024-10-22 19:36:59 +08:00
})
.onRefreshing(() => {
2024-10-23 16:03:00 +08:00
this.onRefresh && this.onRefresh()
2024-10-22 19:36:59 +08:00
})
}
}