一.storage二次封装代码
/**
* Storage 二次封装
*/
import config from '../config' --> namespace:'manager'
export default {
// 将内容写入对应的存储空间
setItem(key, val) {
// 调用获取存储空间
let storage = this.getStorage()
// 将空间内容存储
storage[key] = val
// 根据全局的localStorage的缓存空间名,写入序列化的storage数据,将 JavaScript 值转换为 JSON 字符串
window.localStorage.setItem(config.namespacce, JSON.stringify(storage))
},
// 获取存储及空间方法
getStorage() {
// 获取localStorage的存储空间,数据转换为JavaScript对象,如果没有就设置成对象{}
return JSON.parse(window.localStorage.getItem(config.namespace)||"{}")
},
// 根据key获取对应的存储空间
getItem(key) {
return this.getStorage()[key]
},
// 根据key清空localStorage存储空间内容
clearItem(key) {
let storage = this.getStorage()
delete storage[key]
window.localStorage.setItem(config.namespacce,JSON.stringify(storage))
},
// 清空所有localStorage存储空间内容
clearAll() {
window.localStorage.clear()
}
}
二.理解
1.setItem
- 向info中添加height属性:setItem做了什么?:
- 得到一个对象
(1) 由于getItem得到的是一个字符串,所以要使用JSON.stringify将字符串转化成一个对象,赋值给obj - 用对象的方法添加属性
(2)用obj.height=1.89向obj对象中添加height属性 - 将添加属性后的对象放回info中
(3) 由于setItem的key和value都要满足字符串类型,所以使用JSON.parse将obj对象转化成字符串
(4) 使用setItem将"{name:‘abc’,age:23,height:1.89}"加入info
注意:使用JSON.parse,你的字符串必须符合JSON格式,即键值都必须使用双引号包裹
2.getItem
- 根据key获取对应的存储空间:getItem做了什么?:
- 得到一个对象
(1)由于getItem得到的是一个字符串,所以要使用JSON.stringify将字符串转化成一个对象,赋值给obj - 用对象的方法得到value
(2)使用对象的方法:obj.key得到value
3.clearItem
- 根据key清空localStorage存储空间内容:clearItem做了什么?:
- 得到一个对象
(1)由于getItem得到的是一个字符串,所以要使用JSON.stringify将字符串转化成一个对象,赋值给obj - 用对象的方法删除
(2)使用delete obj.age就将obj对象中的age属性清除了(打印obj可以看出已经清除) - 将删除后的对象放回info中
(3)使用setItem将字符串化的obj对象(JSON.stringify(obj))写入info存储空间
(4)使用getItem获取info的内容验证是否已经清空
三.使用
- setItem
this.$storage.setItem('name', 'kobe')
- getItem
console.log("name:",this.$storage.getItem("name"))
- clearItem
this.$storage.clearItem("name")
- clearAll
this.$storage.clearAll()