ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] ## LocalStorage:页面级UI状态存储 ## 示例 ### 直接使用 ``` let storage = new LocalStorage({ 'PropA': 47 }); // 创建新实例并使用给定对象初始化 let propA = storage.get('PropA') // propA == 47 let link1 = storage.link('PropA'); // link1.get() == 47 let link2 = storage.link('PropA'); // link2.get() == 47 let prop = storage.prop('PropA'); // prop.get() = 47 link1.set(48); // two-way sync: link1.get() == link2.get() == prop.get() == 48 prop.set(1); // one-way sync: prop.get()=1; but link1.get() == link2.get() == 48 link1.set(49); // two-way sync: link1.get() == link2.get() == prop.get() == 49 ``` ## 从UI内部使用@LocalStorageLink ``` // 使LocalStorage可从@Component组件访问 @Entry(storage) @Component struct CompA { // @LocalStorageLink变量装饰器与LocalStorage中的'PropA'属性建立双向绑定 @LocalStorageLink('PropA') storLink1: number = 1; build() { Column({ space: 15 }) { Button(`Parent from LocalStorage ${this.storLink1}`) // initial value from LocalStorage will be 47, because 'PropA' initialized already .onClick(() => this.storLink1 += 1) // @Component子组件自动获得对CompA LocalStorage实例的访问权限。 Child() } } } ``` ## LocalStorageProp 单项绑定 ``` @Component struct Child { // @LocalStorageProp变量装饰器与LocalStorage中的'PropA'属性建立单向绑定 @LocalStorageProp('PropA') storProp2: number = 2; build() { Column({ space: 15 }) { // 当CompA改变时,当前storProp2不会改变,显示47 Text(`Parent from LocalStorage ${this.storProp2}`) } } } ```