Vue3设置缓存:storage.ts

在vue文件使用:

javascript 复制代码
import { Local,Session } from '/@/utils/storage';
// Local
if (!Local.get('字段名')) Local.set('字段名', '字段的值');

// Session 
Session.getToken()

storage.ts文件:

javascript 复制代码
import Cookies from 'js-cookie';

/**
 * window.localStorage 浏览器永久缓存
 * @method set 设置永久缓存
 * @method get 获取永久缓存
 * @method remove 移除永久缓存
 * @method clear 移除全部永久缓存
 */
export const Local = {
	// 查看 v2.4.3版本更新日志
	setKey(key: string) {
		// @ts-ignore
		return `${__NEXT_NAME__}:${key}`;
	},
	// 设置永久缓存
	set<T>(key: string, val: T) {
		window.localStorage.setItem(Local.setKey(key), JSON.stringify(val));
	},
	// 获取永久缓存
	get(key: string) {
		let json = <string>window.localStorage.getItem(Local.setKey(key));
		return JSON.parse(json);
	},
	// 移除永久缓存
	remove(key: string) {
		window.localStorage.removeItem(Local.setKey(key));
	},
	// 移除全部永久缓存
	clear() {
		window.localStorage.clear();
	},
};

/**
 * window.sessionStorage 浏览器临时缓存
 * @method set 设置临时缓存
 * @method get 获取临时缓存
 * @method remove 移除临时缓存
 * @method clear 移除全部临时缓存
 */
export const Session = {
	// 设置临时缓存
	set(key: string, val: any) {
		if (key === 'token' || key === 'refresh_token') {
			Cookies.set(key, val);
		}
		window.sessionStorage.setItem(key, JSON.stringify(val));
	},
	// 获取临时缓存
	get(key: string) {
		if (key === 'token' || key === 'refresh_token') return Cookies.get(key);
		let json = <string>window.sessionStorage.getItem(key);
		return JSON.parse(json);
	},
	// 移除临时缓存
	remove(key: string) {
		if (key === 'token' || key === 'refresh_token') return Cookies.remove(key);
		window.sessionStorage.removeItem(key);
	},
	// 移除全部临时缓存
	clear() {
		Cookies.remove('token');
		Cookies.remove('refresh_token');
		Cookies.remove('bbId');
		window.sessionStorage.clear();
	},
	// 获取当前存储的 token
	getToken() {
		return this.get('token');
	},
	// 获取当前的用户
	getTenant() {
		return Local.get('bbId') ? Local.get('bbId') : 1;
	},
};
相关推荐
陈随易9 分钟前
bun将会支持Bun.image,你怎么看?
前端·后端·程序员
Lyyaoo.21 分钟前
缓存更新策略
缓存
jingqingdai326 分钟前
别用正则格式化 HTML!我用 DOM 遍历实现零风险本地格式化,老项目重构效率直接拉满
前端·重构·html
木斯佳29 分钟前
前端八股文面经大全:腾讯前端实习二、三OC面(2026-04-27)·面经深度解析
前端·状态模式
Python私教41 分钟前
如意Agent日志系统重构:从 print() 大海捞针到结构化可观测性栈
java·前端·重构
We་ct1 小时前
LeetCode 97. 交错字符串:动态规划详解
前端·算法·leetcode·typescript·动态规划
AI进化营-智能译站1 小时前
ROS2 C++开发系列08-传感器数据缓存与指令解析方式之数组、向量与字符串实战
开发语言·c++·缓存·ai
Chengbei111 小时前
轻量化 Web 安全日志分析神器 星川智盾日志威胁检测、地理溯源、MITRE ATT&CK 映射,支持 Windows/macOS/Linux
前端·人工智能·安全·web安全·macos·系统安全·安全架构
风流 少年1 小时前
Python Web框架:FastAPI
前端·python·fastapi