最近因爲做一個功能需要把一些用戶填寫的基本信息保存到瀏覽器的 Local Storage 中,於是找到了一個不錯的工具——xStore,xStore 封裝了 HTML5 的 localStorage 和 sessionStorage 接口,通過它可以很方便地將數據存放在瀏覽器本地的 Local Storage 或 Session Storage;
xStore 項目 GitHub 開源地址:https://github.com/florian/xStore
下面簡要介紹下 xStore 的使用方式
- 創建 LocalStorage 存儲實例:
var local = new xStore("local:", localStorage);
創建 local 實例時傳入了兩個參數,其中第一個參數 "local:" 存放到 Local Storage 後的數據 KEY 前綴,第二個參數表示生成的存儲對象是用於存取 Local Storage 數據;
- 創建 SessionStorage 存儲實例:
var session = new xStore("session:", sessionStorage);
- 存儲數據到 Local Storage:
local.put("author", "Shawearn");
存儲到 Session Storage 與 Local Storage 相似,下面以 Local Storage 爲例,Session Storage 不再贅述;
- 獲取數據:
local.get("author"); // Shawearn
- 移除指定數據:
local.remove("author");
- 清空數據:
local.empty();