Skip to content

vue中Storge的封装使用

utils/storge文件夹中/storge.js

js
class Storage {
  constructor(option) {
    this.storage = option.storage;     //传入localStorage 或 sessionStorage
    this.prefixKey = option.prefixKey; //私有前缀
  }

  getKey(key) {//获取storage全称
    return `${this.prefixKey}${key}`.toLowerCase();
  }

  set(key, value, expire) {
    const stringData = JSON.stringify({
      value,
      time: Date.now(),
      expire: !expire ? new Date().getTime() + expire * 1000 : null,
    });
    this.storage.setItem(this.getKey(key), stringData);
  }

  get(key) {
    const { value } = this.getItem(key, {});
    return value;
  }

  getItem(key, def = null) {
    const val = this.storage.getItem(this.getKey(key));
    if (!val) return def;
    const data = JSON.parse(val);
    const { value, time } = data;
    return { value, time };
  }

  remove(key) {
    this.storage.removeItem(this.getKey(key));
  }

  clear() {
    this.storage.clear();
  }
}

export function createStorage({ prefixKey = "", storage = sessionStorage }) {
  return new Storage({ prefixKey, storage });
}

index.js

js
import { createStorage } from "./storage";

const prefixKey = "y-admin-";//设置私有前缀

export const createLocalStorage = function (option = {}) {
  return createStorage({
    prefixKey: option.prefixKey || "",
    storage: window.localStorage,
  });
};

export const createSessionStorage = function (option = {}) {
  return createStorage({
    prefixKey: option.prefixKey || "",
    storage: window.sessionStorage,
  });
};

export const lStorage = createLocalStorage({ prefixKey });

export const sStorage = createSessionStorage({ prefixKey });

使用

html
<script setup>
import { lStorage } from '@/utils'
const token = 'token'
lStorage.set('token',token)
lStorage.get('token')
lStorage.remove('token')
lStorage.clear()
</script>

storage存储的内容

js
key:'y-admin-token'
value:
{      	"value":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InlsIiwiaWF0IjoxNjY0MzUxMTgwLCJleHAiOjE2NjQzNTQ3ODB9.osuogHhWPVLJgkD4AV9ZpKtDCVAHxOztX34lJxerw3U",
"time": 1664351181581,
"expire": null
}