AppStorage,PersistentStorage與StorageLink
AppStorage是應用全局狀態管理器,數據存儲于內存中,常見的如全局的黑暗模式,StorageLink是用來綁定AppStorage的鍵到ui上的工具,省去了用戶手寫代碼的無聊過程,PersistentStorage可以綁定AppStorage的鍵,自動持久化到磁盤,同時支持多設備同步,也省去了無聊的手寫代碼過程,這個點上真的是非常方便
PersistentStorage.persistProp(‘theme’, ‘system’); 這個代碼直接持久化綁定了AppStorage里面的Theme的值,所以不需要AppStorage再寫一遍存儲邏輯了
// 1. 初始化函數
function initApp() {// 設置持久化屬性PersistentStorage.persistProp('userInput', '初始值');
}// 2. 主頁面組件
@Entry
@Component
struct SimplestDemo {// 雙向綁定到持久化屬性@StorageLink('userInput') input: string = '';aboutToAppear() {initApp(); // 初始化應用狀態}build() {Column() {// 顯示當前值Text(`當前值: ${this.input}`)// 輸入框TextInput({ text: this.input }).onChange((value: string) => {this.input = value;//這里會同時持久化到磁盤里面})// 重置按鈕Button('重置為默認值').onClick(() => {this.input = '初始值';})}}
}
state
頁面或組件內部的數據,用于綁定到UI
數據存儲方案對比
PersistentStorage/Preferences/relationalStore/localStorage /AppStorage
方案 | 數據位置 | 生命周期 | 數據類型支持 | 典型應用場景 | 性能特點 |
---|---|---|---|---|---|
AppStorage | 內存 | 應用運行時 | 任意類型 | 全局狀態共享 | 高速訪問 |
PersistentStorage | 內存+磁盤 | 應用重啟后保持 | 基本類型(string/number/boolean) | 主題/語言設置等小數據持久化 | 自動同步,中等性能 |
Preferences | 磁盤 | 持久化存儲 | 可序列化數據 | 用戶配置、登錄令牌等結構化數據 | 異步操作,適合中小數據 |
relationalStore | 磁盤 | 持久化存儲 | 結構化關系數據 | 通訊錄、消息記錄等復雜數據 | 支持SQL,事務處理 |
localStorage | 內存 | 頁面生命周期 | 任意類型 | 頁面內組件間狀態共享 | 快速,頁面關閉即釋放 |
文件存儲 | 磁盤 | 持久化存儲 | 任意二進制/文本 | 圖片、音視頻、大文件 | 靈活,適合大數據 |
LocalStorage 只限在同一個uiability里面共享數據,跨page需要使用const storage = LocalStorage.getShared();來獲取
簡單全局配置的多設備同步
// 1. 啟用分布式同步(只需一行)
PersistentStorage.persistProp('theme', 'system', true); // 第三個參數 true 啟用同步
// 2. 組件中使用
@Entry
@Component
struct ThemeSetting {// 雙向綁定(自動同步)@StorageLink('theme') theme: string = 'system';
//3.權限配置(module.json5)
{"module": {"requestPermissions": [{"name": "ohos.permission.DISTRIBUTED_DATASYNC","reason": "同步主題設置"}]}
}