因爲項目中常需用到本地storage存儲,複雜的數組、對象等,每次都須要JSON.stringify()
和JSON.parse()
進行序列化、反序列化操做,以爲有點麻煩,再者,存入storage的數值,取出來就變成字符串了,所以,對storage簡單封裝了一下,使取出的值類型和存入時保持一致,也能夠存入整個object對象。git
一、安裝github
npm install pz_storage --save
複製代碼
二、使用npm
import storage from 'pz_storage';
// 存儲單個值
storage.set('name', 'esther');
// 獲取單個值
storage.get('name');
// 刪除單個值
storage.remove('name');
// 清空所有
storage.clear();
// 存儲對象,key - value形式
storage.setList({
a: '1',
b: '2.1',
c: ['a', 'b', 'c'],
d: {
'd-1': 'd-1',
'd-2': 'd-2'
},
e: true,
f: new Date(),
g: function(){
console.log(111);
}
});
// 獲取多個值,傳入數組形式的key
storage.getList(['a', 'b', 'd', 'f']);
// 刪除多個值,傳入數組形式的key
storage.removeList(['a', 'b', 'd', 'f'])
// sessionStorage, api同上
storage.session.set('name', 'esther');
複製代碼
也可直接在HTML頁面引入dist文件夾下的storage.jsapi
<script src="dist/storage.js"></script>
複製代碼
github地址數組