vue项目中对storage进行封装
我们知道Storage本身有API,非常简单的key/val形式的,那么我们为什么还要去封装呢?为什么呢???
- – 就是因为简单,所以无法满足项目需求
 - – Storage只存储字符串,需要人工转换成json对象
 - – Storage只能一次性清空,不能单个清空
 
上代码…

import config from './../config'
export default {
// 获取storage存储对象
    getStorage(){
        // 字符串转化为对象
        return JSON.parse(window.localStorage.getItem(config.namespace) || "{}")
    },
    setItem(key, val) {
        // step1 首先获取storage信息
        let storage = this.getStorage()
        // step2 添加新的缓存对象
        storage[key] = val
        // step3 反序列化转换成字符串存入缓存中
         window.localStorage.setItem(config.namespace, JSON.stringify(storage)
    },
    getItem(key) {
        return this.getStorage()[key]
    },
    clearItem(key) {
        let storage = this.getStorage()
        delete storage[key]
        window.localStorage.setItem(config.namespace, JSON.stringify(storage))
    },
    clearAll() {
        window.localStorage.clear()
    }
}
全局挂载
想要全局调用就在main.js里面挂载一个全局的方法
import storage from './utils/storage.js' const app = createApp(App) app.config.globalProperties.$storage = storage
Vue页面调用
mounted(){
    this.$storage.setItem('name', 'LiMing')
    this.$storage.setItem('userinfo', {"A": "a", "B": "b"})
    console.log('name---', this.$storage.getItem("name"))
    this.$storage.clearItem("name")
    this.$storage.clearAll()
}
以上代码就可以实现复杂的缓存了
            
            



















