@capacitor/preferences
Preferences API 为轻量级数据提供简单的键/值持久化存储。
移动操作系统可能会定期清除 window.localStorage 中设置的数据,因此
应改用此 API。当作为渐进式 Web 应用运行时,此 API 将回退到使用 localStorage。
此插件将在 iOS 上使用
UserDefaults,
在 Android 上使用
SharedPreferences。
如果应用被卸载,存储的数据将被清除。
注意:此 API 不 旨在用作本地数据库。如果你的应用 存储大量数据、具有高读写负载或需要复杂查询, 我们建议考虑使用基于 SQLite 的解决方案。一个这样的解决方案是 Ionic Secure Storage,一个具有完整加密支持的基于 SQLite 的引擎。Capacitor Community 还构建了许多其他存储引擎。
安装
npm install @capacitor/preferences@latest-5
npx cap sync
示例
import { Preferences } from '@capacitor/preferences';
const setName = async () => {
await Preferences.set({
key: 'name',
value: 'Max',
});
};
const checkName = async () => {
const { value } = await Preferences.get({ key: 'name' });
console.log(`你好 ${value}!`);
};
const removeName = async () => {
await Preferences.remove({ key: 'name' });
};
使用 JSON
Preferences API 只支持字符串值。但是,你可以使用 JSON,方法是在调用 set() 之前对对象进行 JSON.stringify,然后对 get() 返回的值进行 JSON.parse。
此方法也可用于存储非字符串值,例如数字和布尔值。
API
configure(...)
configure(options: ConfigureOptions) => Promise<void>
在运行时配置偏好设置插件。
值为 undefined 的选项将不会被使用。
| 参数 | 类型 |
|---|---|
options | |
自从: 1.0.0
get(...)
get(options: GetOptions) => Promise<GetResult>
从偏好设置中获取指定键的值。
| 参数 | 类型 |
|---|---|
options | |
返回:
Promise<GetResult>
自从: 1.0.0
set(...)
set(options: SetOptions) => Promise<void>
在偏好设置中为指定键设置值。
| 参数 | 类型 |
|---|---|
options | |
自从: 1.0.0
remove(...)
remove(options: RemoveOptions) => Promise<void>
从偏好设置中移除指定键的值(如果有)。
| 参数 | 类型 |
|---|---|
options | |
自从: 1.0.0
clear()
clear() => Promise<void>