数据增加之后 渲染的数据也增加
import { BusinessError } from '@kit.BasicServicesKit';
import { geoLocationManager } from '@kit.LocationKit';
import { App } from '@kit.ArkUI';
class punchRecord{
time: string=''
local: string=''
constructor(time: string='',local: string='') {
this.time=time
this.local=local
}
}
//持久化存储
PersistentStorage.persistProp('aa',new punchRecord())
@Entry
@Component
struct DakaPage {
// 打卡按钮点击处理函数
onPunchCard(): void {
this.getCurrentLocation().then((location) => {
this.time = new Date().toLocaleString();
// console.info('aabb',this.time)
this.local = `Lat: ${location.latitude}, Lng: ${location.longitude}`;
// console.info('aabb',this.local)
// 将新记录添加到打卡记录数组
let pun:punchRecord=new punchRecord(this.time,this.local)
this.punchRecords.push(pun);
console.info('aacc',JSON.stringify(this.punchRecords))
// 保存打卡记录到本地存储
AppStorage.setOrCreate('aa',this.punchRecords)
console.log('aab',JSON.stringify(this.punchRecords))
// 更新界面
// this.update();
}).catch((error:BusinessError) => {
console.error('Failed to get location: ' + JSON.stringify(error));
});
}
//更新界面
update(){}
// 获取当前地理位置
async getCurrentLocation(): Promise<geoLocationManager.Location> {
const request: geoLocationManager.SingleLocationRequest = {
locatingPriority: geoLocationManager.LocatingPriority.PRIORITY_LOCATING_SPEED,
locatingTimeoutMs: 10000
};
this.local= JSON.stringify(await geoLocationManager.getCurrentLocation(request))
return await geoLocationManager.getCurrentLocation(request);
}
// 定义一个打卡记录数组,数组中的每个元素都是包含 time 和 location 的对象
@State punchRecords: punchRecord[]= []
// @State arr: punchRecord= new punchRecord()
@State local:string=''
@State time:string=''
//取出数据
@StorageProp('aa') aa:punchRecord[]=[]
// 界面构建
build() {
Column() {
Button('打卡')
.onClick(() => this.onPunchCard())
.width('100%')
.height(50)
.backgroundColor('#00AAFF')
.fontColor('#FFFFFF')
.margin({ top: 20 })
//如果数组存在就显示
if (this.aa[0]){
ForEach(this.aa, (item: punchRecord) => {
Column(){
Text(`打卡时间: ${item.time}`)
Text(`地理位置: ${item.local}`)
.fontSize(14)
.fontColor('#666666')
.margin({ bottom: 10 })
} .backgroundColor(Color.Pink).height(40)
.width('90%')
})
}
}.height('100%')
.width('100%')
}
}