在vue项目中封装LocalStorage、sessionStorage为公共方法

3,145 阅读1分钟

封装本地存储的目的就是为了方便存取数据、节省代码量,vuex调用中也是为了保持vuex的数据长久性,如下。我是用的是ts封装,如果你项目中没有ts依赖就将括号里带冒号的形参后面的代码删掉即可,或者安装ts依赖

/**
 * window.localStorage 浏览器永久缓存
 * @method set 设置永久缓存
 * @method get 获取永久缓存
 * @method remove 移除永久缓存
 * @method clear 移除全部永久缓存
 */
export const Local = {
	// 设置永久缓存
	set(key: string, val: any) {
		window.localStorage.setItem(key, JSON.stringify(val));
	},
	// 获取永久缓存
	get(key: string) {
		let json: any = window.localStorage.getItem(key);
		return JSON.parse(json);
	},
	// 移除永久缓存
	remove(key: string) {
		window.localStorage.removeItem(key);
	},
	// 移除全部永久缓存
	clear() {
		window.localStorage.clear();
	},
};

/**
 * window.sessionStorage 浏览器临时缓存
 * @method set 设置临时缓存
 * @method get 获取临时缓存
 * @method remove 移除临时缓存
 * @method clear 移除全部临时缓存
 */
export const Session = {
	// 设置临时缓存
	set(key: string, val: any) {
		window.sessionStorage.setItem(key, JSON.stringify(val));
	},
	// 获取临时缓存
	get(key: string) {
		let json: any = window.sessionStorage.getItem(key);
		return JSON.parse(json);
	},
	// 移除临时缓存
	remove(key: string) {
		window.sessionStorage.removeItem(key);
	},
	// 移除全部临时缓存
	clear() {
		window.sessionStorage.clear();
	},
	// 获取临时缓存
	getCorporationId() {
		let json: any = window.sessionStorage.getItem('userInfo');
		const data = JSON.parse(json);
		if (!data || !data.user || !data.user.corporation) {
			return '';
		}
		return data.user.corporation.corporation_id;
	},
};