# store2本地儲存套件分享 ### store2是什麼? 平常我們在使用localStorage時,在儲存以及取值時還需要使用JSON語法將資料進行轉換。 ``` /** 儲存 */ const country = [ {farmers: Tom} ] const countryString = JSON.stringify(country); localStorage.setItem('countryItem',countryString); /** 取得 */ const getStoreString = localStorage.getItem('countryItem'); const transferCountry = JSON.parse(getStoreString); ``` 而store2完全解決了這個問題,在我們取值後就可以直接使用,不需要再額外的做轉換的處理。 ``` /** 儲存 */ store.set('countryItem', country); // 直接設定即可 套件會幫忙轉換 /** 取得 */ const storeCountry = store.get('countryItem'); ``` 就像以上這樣,程式碼不會在落落長,乾淨簡潔。 除此之外還有提供一些API可以供操作。 ### 常用API - **store.setAll(data[, overwrite])** 可以一次儲存多筆資料,overwrite為true時則覆蓋原有儲存的資料。 ``` store.setAll({ key1: 'value1', key2: 'value2' }); ``` - **store.getAll([fillObj])** 一次取得多筆資料 ``` store.getAll(); ``` - **store.transact(key, fn[, alt])** 針對特定儲存資料進行操作及處理 ``` store.transact('myKey', (currentValue) => { currentValue.age = 30; }); ``` - **store.clear()** 如果有使用namespace的API建立儲存空間,則清除該儲存空間的所有資料。 如果沒有則清除所有的localStorage的資料。 ``` const myStore = store.namespace('myApp'); myStore.clear(); // 只會清除 'myApp' 命名空間下的數據 ``` - **store.has(key)** 檢查指定有儲存資料存在 回傳為boolean ``` const exists = store.has('myKey'); ``` - **store.remove(key[, alt])** 移除指定key的儲存資料 ``` // 假設 'someKey' 不存在於存儲中 var result = store.remove('someKey','defaultValue'); // 由於 'someKey' 不存在,所以 result 將會是'defaultValue' console.log(result); // 輸出: 'defaultValue' ``` - **store.each(fn[, fill])** 歷遍所有儲存的資料 ``` store.each(function(key, value) { console.log(key, ':', value); }); ``` - **store.add(key, data[, replacer])** ``` // 假設原始值是一個數組 store.set('myArray', [1, 2, 3]); store.add('myArray', [4, 5]); // 現在 'myArray' 是 [1, 2, 3, 4, 5] ``` - **store.keys([fillList])** ``` const storedKeys = store.keys(); console.log(storedKeys); // 這將顯示類似於 ["key1", "key2"] 的輸出 ``` - **store.size()** ``` const numberOfKeys = store.size(); console.log(numberOfKeys); // 這將顯示存儲資料的數量,例如 2 ``` - **store.clearAll()** 清除所有儲存在localStorage的資料 ``` store.clearAll(); ``` ### sessionStorage store2除了可以操作localStorage外,也有提供sessionStorage的操作。操作方法也與localStorage差不多,只需要在使用的API前加入session即可。 ``` store.session.set('key', 'value'); ``` [npm連結](https://www.npmjs.com/package/store2)