@nativescript-use/nativescript-localstorage
添加插件描述
npm i --save @nativescript-use/nativescript-localstorage

@nativescript-use/nativescript-localstorage

npm install @nativescript-use/nativescript-localstorage

像浏览器一样使用 localStorage。这个库在 NativeScript 的背后使用了 ApplicationStorage

用法

import localStorage from '@nativescript-use/nativescript-localstorage';

localStorage.setItem('myKey', "myValue");
localStorage.getItem('myKey'); // -> "myValue"
localStorage.has('myKey');
localStorage.removeItem('myKey');
localStorage.length();
localStorage.clear();

扩展 LocalStorage 类

您可以在 ApplicationSettings 中为所有条目定义一个带有前缀的存储,如下所示:

// BusinessStorage.ts
import { LocalStorage } from '@nativescript-use/nativescript-localstorage';

export enum BusinessKeys {
NAME = 'name',
}

class BusinessStorage extends LocalStorage<BusinessKeys> {
prefix = '_businnes_.';
}
const businessStorage = new BusinessStorage();
export default businessStorage;

然后可以这样使用。

import businessStorage, { BusinessKeys } from './BusinessStorage';

businessStorage.setItem(BusinessKeys.NAME, 'MyBusiness');
businessStorage.getItem(BusinessKeys.NAME);

这将生成 ApplicationSettings 中的以下条目

_businnes_.name = 'MyBusiness'

类型声明

declare class LocalStorage<K extends string> {
protected prefix: string;
getItem<T>(key: K): T;
setItem(key: K, data: any): void;
has(key: K): boolean;
removeItem(key: K): void;
length(): number;
clear(): void;
}
export declare const localStorage: LocalStorage<string>;

许可协议

Apache 许可协议第 2 版