官方关于LocalStorage的说明: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V2/arkts-localstorage-0000001524537149-V2
说了些页面间,组建内关于LocalStorage的使用方法。这里就不再赘述。
但是关于如何在 UIAbility和 Page之间传递没有说。为啥我会这么问呢,因为我需要这么传:
javascript
onWindowStageCreate(windowStage: window.WindowStage): void {
windowStage.loadContent('pages/MainPage', localStorage);
}
我需要把 UIAbility中的参数传递到第一个需要加载到页面中去,而且 windowStage.loadContent() 方法本来就可以传递一个 localStorage 的。
也就是如何将LocalStorage实例从UIAbility共享到一个或多个视图。
javascript
export default class MainAbility extends UIAbility {
localStorage = new LocalStorage();
async onCreate(want: Want): Promise<void> {
if (want?.uri != null && want.uri.length > 0) {
let routePage = want.parameters?.['page'] as string;
let routePageParam = want.parameters as Record<string, object>
this.localStorage.clear()
this.localStorage.setOrCreate('page', routePage)
this.localStorage.setOrCreate('params', routePageParam)
}
}
onWindowStageCreate(windowStage: window.WindowStage): void {
windowStage.loadContent('pages/MainPage', this.localStorage);
}
}
页面中:
javascript
let storage = LocalStorage.getShared()
@Entry(storage)
@Component
struct MainPage {
@State notificationState: string = ''
private clickBackTimeRecord: number = 0;
@LocalStorageProp('page') page: string = ''
@LocalStorageProp('params') params: Record<string, object> = {}
}