LocalStorage和AppStorage都是运行时的内存,在应用退出后就没有了,如果要在应用退出后再次启动依然能保存选定的结果,这就需要用到PersistentStorage。
保存基本类型
number, string, boolean, enum 等简单类型都支持
核心步骤:
- 初始化PersistentStorage
- 通过 AppStorage 获取并修改数据
- 重启应用,检测结果
PersistentStorage.persistProp<string>('info','怎么感觉呆呆的')
@Entry
@Component
struct PersistentStoragePage01 {
@StorageLink('info')
info:string=''
build() {
Row() {
Column() {
Text(this.info)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(()=>{
this.info+='!'
})
}
.width('100%')
}
.height('100%')
}
}
保存复杂类型
支持的复杂类型:
- 可以被JSON.stringify()和JSON.parse()重构的对象。例如Date, Map, Set等内置类型则不支持,以及对象的属性方法不支持持久化。自己定义的 class、interface 基本都是支持的
不允许的类型和值有:
- 不支持嵌套对象(对象数组,对象的属性是对象等)。因为目前框架无法检测AppStorage中嵌套对象(包括数组)值的变化,所以无法写回到PersistentStorage中。
- 不支持 undefined 和 null
interface FoodInfo{
name:string
price:number
}
PersistentStorage.persistProp<FoodInfo[]>('foods',[
{name:'清炒西兰花',price:10},
{name:'凉拌西兰花',price:15},
{name:'生嚼西兰花',price:14},
])
@Entry
@Component
struct PersistentStoragePage {
@StorageLink('foods')
foods:FoodInfo[]=[]
build() {
Row() {
Column() {
Text(JSON.stringify(this.foods))
.fontSize(20)
.fontWeight(FontWeight.Bold)
.onClick(()=>{
// this.foods[0].name='花菜炒蛋'
this.foods[0] = {
name:'花草炒蛋',
price:29
}
})
}
.width('100%')
}
.height('100%')
}
}