localstorage封装!

最近整理框架时候,封装了一份local操作,分享下  需要的人可以使用哦

/**
* @description globelLocal操作
*/
import { objectTool } from 'mwutil'
class Local {
constructor (name) {
this.store = window.localStorage
this.storeName = name
}
// 设置一个local
set (key, value) {
//存储
let storeData = this.store.getItem(this.storeName)
if(!storeData){
this.init()
storeData = this.store.getItem(this.storeName)
}
storeData = JSON.parse(storeData)
storeData.data[key] = value
this.store.setItem(this.storeName, JSON.stringify(storeData))
return storeData.data
}
// 批量设置local
batchSet (obj) {
if (!objectTool.isObject(obj)) {
return
}
for (const key in obj) {
this.set(key, obj[key])
}
}
// 获取一个local
get (key) {
//读取
let result = this.getAll()
if (!result) {
return null
}
return result[key]
}
// 批量获取local
batchGet () {
let result = {}
const allLocal = this.getAll()
if (!allLocal) {
return result
}
for (var i = 0; i < arguments.length; i++) {
const item = arguments[i]
result[item] = allLocal[item]
}
return result
}
// 获取全部
getAll () {
let storeData = this.store.getItem(this.storeName)
if(!storeData){
return null
}
storeData = JSON.parse(storeData)
return storeData.data
}
// 删除一个
remove (key) {
//读取
let storeData = this.store.getItem(this.storeName)
if(!storeData){
return
}
storeData = JSON.parse(storeData)
delete storeData.data[key]
this.store.setItem(this.storeName,JSON.stringify(storeData))
return storeData.data
}
// 清除
clear () {
//清除对象
this.store.removeItem(this.storeName)
}
// 初始化
init () {
this.store.setItem(this.storeName,'{"data":{}}')
}
}
export default new Local('__global')

注: 因为我在项目中只是需要global local  你们用的时候可以直接吧class export 这样就可以在使用的地方进行相应nameSpace

注2: mwutil为我写的一个库  

Object.isObj 为判断是否是对象的方法,不想用库的可以自行改一下判段,不过我还是希望库能被大家使用

使用方法:

// 批量获取
globalLocal.batchGet('a', 'b')
// 单个获取
globalLocal.get('token')
// 清空
globalLocal.clear()
// 批量设置
globalLocal.batchSet({
  a: aValue,
  b: bValue    
}
// 单个设置
globalLocal.set(a, aValue)
// 获取全部
globalLocal.getAll()
// 删除一个
globalLocal.remove(a)

 

posted @ 2020-08-20 14:12  金振宗  阅读(871)  评论(0编辑  收藏  举报