UNPKG

project-general-tools

Version:

项目开发通用工具类封装

102 lines (101 loc) 3.76 kB
"use strict"; /* * @Author: Mad Dragon 395548460@qq.com * @Date: 2020年3月21日 * @explanatory: 存储localStorage */ Object.defineProperty(exports, "__esModule", { value: true }); function isNull(obj) { return typeof obj === 'undefined' || obj === null; } function trim(str) { return isNull(str) ? '' : (`${str}`).replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); } exports.default = { // 存储localStorage setItem(key, content) { if (!key && typeof window === 'undefined') return; let contentTxt = content; if (typeof content !== 'string') { contentTxt = JSON.stringify(content); } window.localStorage.setItem(key, contentTxt); }, // 获取localStorage getItem(key) { if (!key && typeof window === 'undefined') return ''; return window.localStorage.getItem(key) || ''; }, // 删除localStorage removeItem(key) { if (!key && typeof window === 'undefined') return; window.localStorage.removeItem(key); }, // 从localStorage删除所有保存的数据 clear() { window.localStorage.clear(); }, // 获取所有的 缓存数据 getAll() { const len = localStorage.length; // 获取长度 // console.log(len); // 输出5 const arr = []; // 定义数据集 for (let i = 0; i < len; i += 1) { // 获取key 索引从0开始 const getKey = localStorage.key(i) || ''; // 获取key对应的值 const getVal = localStorage.getItem(getKey); // 放进数组 arr[i] = { key: getKey, val: getVal }; } return arr; }, // 删除指定 key匹配的数据 removeDataFromKey(key = '') { const getAll = this.getAll(); for (let i = 0, len = getAll.length; i < len; i += 1) { if (trim(getAll[i].key).indexOf(key) !== -1) { this.removeItem(getAll[i].key); } } } }; /** * _ooOoo_ * o8888888o * 88' . '88 * (| -_- |) * O\ = /O * ____/`---'\____ * .' \\| |// `. * / \\||| : |||// \ * / _||||| -:- |||||- \ * | | \\\ - /// | | * | \_| ''\---/'' | | * \ .-\__ `-` ___/-. / * ___`. .' /--.--\ `. . __ * .'' '< `.___\_<|>_/___.' >'''. * | | : `- \`.;`\ _ /`;.`/ - ` : | | * \ \ `-. \_ __\ /__ _/ .-` / / * ======`-.____`-.___\_____/___.-`____.-'====== * `=---=' * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ * 佛祖保佑 永无BUG * 佛曰: * 写字楼里写字间,写字间里程序员; * 程序人员写程序,又拿程序换酒钱。 * 酒醒只在网上坐,酒醉还来网下眠; * 酒醉酒醒日复日,网上网下年复年。 * 但愿老死电脑间,不愿鞠躬老板前; * 奔驰宝马贵者趣,公交自行程序员。 * 别人笑我忒疯癫,我笑自己命太贱; * 不见满街漂亮妹,哪个归得程序员? * * Mad Dragon 395548460@qq.com */