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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM