內(nèi)容概要
使用ES6語法科雳,封裝名為storageData的class哮洽,并有兩個(gè)子類localData與saveData
示范在vue單文件組件導(dǎo)入class并使用
關(guān)鍵字:localstorage ES6 class封裝繼承多態(tài)
分析
使用本地緩存記錄數(shù)據(jù)唐全,可以通過cookie或者localStorage來存儲(chǔ)(現(xiàn)在基本用loaclStorage了)安券。
使用sessionStorage可保存數(shù)據(jù)至本次會(huì)話結(jié)束悉盆。
localStorage只能存儲(chǔ)字符串鄙麦,需要對(duì)象字符串頻繁轉(zhuǎn)換典唇,本次工具類中做了JSON與Object的互相轉(zhuǎn)換,可以直接傳入傳出對(duì)象胯府。
可能需要設(shè)置數(shù)據(jù)聲明周期介衔,一定時(shí)間后使數(shù)據(jù)失效,例如記住密碼時(shí)長(zhǎng)骂因,長(zhǎng)時(shí)間不操作需要重新登錄等炎咖。
組件化與復(fù)用:這種常用的方法,我們最好寫一個(gè)工具類,或者公共方法乘盼。
類的封裝
storageData父類
含有4個(gè)屬性升熊,一個(gè)判斷目標(biāo)數(shù)據(jù)是否存在的方法
/*
* @name String
* the key of storage
*
* @data Object
* the data what you want to save
*
* @writeTime Number
* a timestamp of when you write
*
* @period Number
* a timestamp how long the data exist
*
* */
class storageData {
constructor(name, data, timestamp) {
this.name = name
this.data = data
this.writeTime = Number (new Date())
this.period = timestamp
}
static isNotExist(data) {
return data === null || typeof(data) === 'undefined'
}
}
localData子類
繼承父類屬性,含一個(gè)存儲(chǔ)方法绸栅,含兩個(gè)靜態(tài)方法级野,一個(gè)用來取數(shù)據(jù),一個(gè)用來檢查數(shù)據(jù)生命周期
export class localData extends storageData{
constructor(name, map, timestamp) {
super(name, map, timestamp)
}
save() {
let saveData = this.data
saveData.writeTime = this.writeTime
saveData.period = this.period
let dataStr = JSON.stringify(saveData)
localStorage.setItem(this.name, dataStr)
}
static get(name) {
let dataJSON = localStorage.getItem(name)
/* End directly when the target does not exist */
if(this.isNotExist(dataJSON)) {
return null
}
let data = JSON.parse(dataJSON)
/* When the existence period of the data is undefined, it is considered as permanent */
if(this.isNotExist(data.period)) {
return data
}
/* Release data if the data declaration period ends */
if(this.isOutPeriod(data)) {
localStorage.removeItem('data')
data = null
}
return data
}
static isOutPeriod(data) {
let readTime = Number (new Date())
if ((readTime - data.writeTime) > data.period) {
return true
}
return false
}
}
sessionData子類略粹胯,與localData 95%一致
類的使用
script中導(dǎo)入子類
import {localData, sessionData} from "../../tools/storage"
let data = {
es6: 'good',
markdown: 'like',
bug: 'fuck'
}
// 存儲(chǔ)30秒
let thinker= new localData('izeya', data, 1000 * 30)
thinker.save()
// 取數(shù)據(jù)(靜態(tài)方法可以直接用類名調(diào)用)
let localTinker = localData.get('thinker')
聽說愛點(diǎn)贊的人蓖柔,bug都不會(huì)太多