UNPKG

ptool

Version:

vue项目开发通用工具类封装

71 lines (70 loc) 2.04 kB
"use strict"; /** * @FileName lStorage.ts * @Author Mad Dragon <395548460@qq.com> * @Version V 0.0.1 * @Date 2021/4/13 11:40 * @Title 存储localStorage * @Desc **/ Object.defineProperty(exports, "__esModule", { value: true }); const isNull = (obj) => typeof obj === 'undefined' || obj === null; const trim = (str) => isNull(str) ? '' : (`${str}`).replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); const 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; }; const removeItem = (key) => { if (!key && typeof window === 'undefined') return; window.localStorage.removeItem(key); }; const 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); }; const getItem = (key) => { if (!key && typeof window === 'undefined') return ''; return window.localStorage.getItem(key) || ''; }; const removeDataFromKey = (key = '') => { const all = getAll(); for (let i = 0, len = all.length; i < len; i += 1) { if (trim(all[i].key).indexOf(key) !== -1) { removeItem(all[i].key); } } }; exports.default = { // 存储localStorage setItem, // 获取localStorage getItem, // 删除localStorage removeItem, // 从localStorage删除所有保存的数据 clear: () => window.localStorage.clear(), // 获取所有的 缓存数据 getAll, // 删除指定 key匹配的数据 removeDataFromKey };