可参考如下代码,变量更改后会自动更新到相应的persistentstorage,退出应用后也会取最新的值class NewsColumn { title: string = ''; id: number = 0; constructor(title: string, id: number) { this.title = title; this.id = id; } } let columnList: NewsColumn[] = [ new NewsColumn("推荐", 0), new NewsColumn("要闻", 2331), new NewsColumn("时政", 2257), new NewsColumn("党建", 2258), new NewsColumn("人事", 2177), new NewsColumn("时评", 2259), new NewsColumn("视频", 2586), new NewsColumn("服务", 1020), new NewsColumn("文化", 3119), ] PersistentStorage.persistProp("newsColumn",columnList); PersistentStorage.persistProp('testNum', 20); @Entry @Component struct Storage { @State message: string = 'Hello World'; @StorageLink('testNum') testNum: number = 10; @StorageLink('newsColumn') columnList:NewsColumn[] = [] aboutToAppear(): void { console.log('newsColumn ' + JSON.stringify(this.columnList)); } build() { Row() { Column() { Text(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) ForEach(this.columnList, (item: NewsColumn, index: number) => { Column() { Text(item.title) .fontSize('15vp') .opacity(0.8) .fontWeight(400) .fontColor(Color.Black) }.onClick(() => { }) }) Text(`${this.testNum}`) .onClick(() => { // 应用退出时会保存当前结果。重新启动后,会显示上一次的保存结果 this.testNum += 1; this.columnList.splice(1,0,new NewsColumn('文化' + this.testNum,1)) }) } } .height('100%') } }
可参考如下代码,变量更改后会自动更新到相应的persistentstorage,退出应用后也会取最新的值