ts封装localstorage\sessionstorage

封装文件

enum CacheType {
  Local,
  Session
}

class Cache{
  storage:Storage
  constructor(type:CacheType) {
    this.storage = type===CacheType.Local?localStorage:sessionStorage
  }
  setCache(key:string,value:any){
    if(value){
      this.storage.setItem(key,JSON.stringify(value))
    }
  }
  getCache(key:string){
    const value=this.storage.getItem(key)
    if(value){
      return JSON.parse(value)
    }
  }
  removeCache(key:string){
    this.storage.removeItem(key)
  }
  clear(){
    this.storage.clear()
  }
}

const localCache= new Cache(CacheType.Local)
const sessionCache= new Cache(CacheType.Session)

export {localCache,sessionCache}

使用

import {localCache } from '@/utils/cache'

localCache.setCache('token',res.token)//res.token为具体数值

你可能感兴趣的:(前端,vue.js,typescript)