鸿蒙HarmonyOS Next 如何使用LocalStorage本地存储

发布于 1周前 作者 gougou168 最后一次编辑是 5天前 来自 鸿蒙OS

鸿蒙HarmonyOS Next 如何使用LocalStorage本地存储


定义LocalStorage的地方,并导出

cke_416.png在某个Entry修饰的页面中,可以获取到foods_name,如图

cke_4172.png

在另一Entry修饰的页面中,却是 undefined

cke_7863.png

7 回复

//Foods.ets

/**
* [@Author](/user/Author) csx
* [@DateTime](/user/DateTime) 2024/6/14 12:35:06
* [@TODO](/user/TODO) Foods
*/

interface FoodsInfo {
foods_name: string;
foods_price: number;
}

export class FoodsInfoModel implements FoodsInfo {
foods_name: string = '';
foods_price: number = 26;

constructor(foods?: FoodsInfo) {
if (foods) {
this.foods_name = foods.foods_name;
this.foods_price = foods.foods_price;
}
}
}

const foods = new FoodsInfoModel({
foods_name: '醋溜白菜',
foods_price: 20
})

const foodNo2 = new FoodsInfoModel({
foods_name: '肉末蒸蛋',
foods_price: 11
})


export const csxStore = new LocalStorage();

csxStore.setOrCreate("foodsNo1", foods);
csxStore.setOrCreate("foodsNo2", foodNo2);

//Demo1

/**
* [@Author](/user/Author) csx
* [@DateTime](/user/DateTime) 2024/6/14 12:51:06
* [@TODO](/user/TODO) Demo1
*/
import { csxStore, FoodsInfoModel } from './Foods'

[@Entry](/user/Entry)(csxStore)
[@Component](/user/Component)
export struct Demo1 {
[@LocalStorageProp](/user/LocalStorageProp)("foodsNo1") foodsNo1: FoodsInfoModel = new FoodsInfoModel();

build() {
Text(this.foodsNo1.foods_name)
}
}

//Demo2

/**
* [@Author](/user/Author) csx
* [@DateTime](/user/DateTime) 2024/6/14 12:51:06
* [@TODO](/user/TODO) Demo1
*/
import { csxStore, FoodsInfoModel } from './Foods'

[@Entry](/user/Entry)(csxStore)
[@Component](/user/Component)
export struct Demo2 {
[@LocalStorageProp](/user/LocalStorageProp)("foodsNo1") foodsNo1: FoodsInfoModel = new FoodsInfoModel();
[@LocalStorageProp](/user/LocalStorageProp)("foodsNo2") foodsNo2: FoodsInfoModel = new FoodsInfoModel();

build() {
Column() {
Text(this.foodsNo1.foods_name)
Text(this.foodsNo2.foods_name)
}
}
}

我这么写没问题啊,代码你试一下

感谢大佬,不过我有个疑问,A页面通过LocalStorageLink接受一个变量,那B页面也通过LocalStorageLink接收该变量并修改它,那A页面中该变量按理说是不是也应该变化

@旺旺崔冰冰

尝试将

cke_2190.png

换成

[@Entry](/user/Entry)({storage: LocalStorage.getShared() })
[@LocalStorageProp](/user/LocalStorageProp)('foodsNo1') options: xxxxxx= new efAlertOptions();

你这个语法上不通过,报错了@Entry({storage: LocalStorage.getShared() } Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals)

LocalStorage在鸿蒙(HarmonyOS)Next中,通常指的是一种在本地存储数据的机制,类似于Web开发中的LocalStorage。鸿蒙系统支持类似的功能,允许开发者在应用内部持久化存储键值对数据。这些数据保存在用户设备的本地存储中,直到被显式删除。开发者需要遵循鸿蒙的开发文档和API指南来正确实现和使用LocalStorage功能。如果问题依旧没法解决请加我微信,我的微信是itying888。

回到顶部