UNPKG

ptool

Version:

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

489 lines (488 loc) 15.4 kB
"use strict"; /** * @FileName tools.ts * @Author Mad Dragon <395548460@qq.com> * @Version V 0.0.1 * @Date 2021/4/13 13:18 * @Title 通用工具类 * @Desc **/ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const element_ui_1 = __importDefault(require("element-ui")); require("element-ui/lib/theme-chalk/index.css"); /* eslint-disable */ const utils = { url: { getQuery() { const hash = location.hash || ''; if (!hash) return {}; const hashArr = hash.split('#'); const url = hashArr[hashArr.length - 1]; const urlArr = url.split('?'); const query = urlArr[urlArr.length - 1]; const queryArr = query.split('&'); const params = {}; queryArr.forEach((item) => { const paramArr = item.split('='); params[paramArr[0]] = paramArr[1] || ''; }); return params; } }, getUUID(len, radix) { const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''); const uuid = []; let i; radix = radix || chars.length; if (len) { for (i = 0; i < len; i += 1) uuid[i] = chars[0 | Math.random() * radix]; } else { let r; uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'; uuid[14] = '4'; for (i = 0; i < 36; i += 1) { if (!uuid[i]) { r = 0 | Math.random() * 16; uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r]; } } } return uuid.join(''); }, getResult(arr = [], id = '', find = 'id', result = 'value') { let value = ''; if (id === undefined || id === null || !find || !result) { return ''; } arr.map((e) => { if (e[find] === id) { value = e[result]; } return e; }); return value; }, object: { isObject(obj) { return typeof obj === 'object'; }, isFunction(obj) { return typeof obj === 'function'; }, isArray(obj) { return this.isNotNull(obj) && obj.constructor === Array; }, isNull(obj) { return typeof obj === 'undefined' || obj === null || this.length(obj) === 0; }, isNotNull(obj) { return !this.isNull(obj); }, length(obj) { let count = 0; for (const i in obj) { // 如果包含除它的原型本身之外的属性 if (Object.prototype.hasOwnProperty.call(obj, i)) { count += 1; } } return count; }, getChildrenPath(obj, c, k) { if (this.isNull(obj)) { return null; } if (obj === c) { return k; } if (this.isObject(obj)) { let v; for (const key in obj) { if (!Object.prototype.hasOwnProperty.call(obj, key)) continue; v = this.getChildrenPath(obj[key], c, key); if (utils.string.isNotBlank(v)) { return `${utils.string.isNotBlank(k) ? `${k}.` : ''}${v}`; } } } return null; }, merge(t, s, mergeArray = false) { for (const k in s) { if (!Object.prototype.hasOwnProperty.call(s, k) || typeof s[k] === 'undefined' || s[k] === null) continue; const item = s[k]; switch (item.constructor) { case Object: { if (t[k] && t[k].constructor === Object) { this.merge(t[k], item); } else { t[k] = item; } break; } case Array: { if (item.length < 1) { break; } if (mergeArray && t[k] && t[k].constructor === Array) { t[k] = [...t[k], ...item]; } else { t[k] = item; } break; } case String: { if (item.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '').length > 0) { t[k] = item; } break; } default: { t[k] = item; } } } return t; } }, string: { trim(str) { return utils.object.isNull(str) ? '' : (`${str}`).replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); }, isBlank(str) { return utils.object.isNull(str) || this.trim(str).length === 0; }, isNotBlank(str) { return !this.isBlank(str); }, isEmpty(str) { return utils.object.isNull(str) || (`${str}`).length === 0; }, isNotEmpty(str) { return !this.isEmpty(str); }, equalsIgnoreCase(a, b) { if (utils.object.isNull(a) || utils.object.isNull(b)) { return false; } return (`${a}`).toLowerCase() === (`${b}`).toLowerCase(); } }, list: { isEmpty(l) { return utils.object.isNull(l) || l.length < 1; }, isNotEmpty(l) { return !utils.list.isEmpty(l); }, stringToList(s) { const txt = typeof s === 'string' ? s.split(',') : s; return s && s.length > 0 ? txt : []; }, find(l, k, v, j) { const n = []; if (utils.list.isNotEmpty(l)) { for (let i = 0, len = l.length, r = l[i]; i < len; i += 1) { if (j ? r[k] === v : `${r[k]}` === `${v}`) n.push(r); } } return n; }, indexOf(l, k, v, b, j) { let n = -1; if (utils.list.isNotEmpty(l)) { for (let i = b || 0, len = l.length, r = l[i]; i < len; i += 1) { if (j ? r[k] === v : `${r[k]}` === `${v}`) { n = i; break; } } } return n; }, dedupe(array) { return Array.from(new Set(array)); }, remove(arr, key) { // @ts-ignore const index = arr.indexOf(key); if (index > -1) { arr.splice(index, 1); } }, // 数组排序 配合 arr.sort(compare('age')) compare(property) { return function (a, b) { var value1 = a[property]; var value2 = b[property]; return value1 - value2; //升序,降序为value2 - value1 }; } }, map: { mapsExtVal(maps, key) { const list = []; for (let i = 0, len = maps.length; i < len; i += 1) { list.push(maps[i][key]); } return list; }, listToMap(list, key) { if (utils.object.isNull(list) || utils.string.isEmpty(key)) { return null; } const map = {}; for (let i = 0, len = list.length; i < len; i += 1) { const row = list[i]; map[row[key]] = row; } return map; }, isEqualForString(a, b) { return utils.map.isEqual(a, b, null, true); }, isEmpty(m) { return utils.object.isNull(m) || this.keys(m).length < 1; }, isNotEmpty(m) { return !this.isEmpty(m); }, isEqual(a, b, isWeak, isString) { if (utils.object.isNull(a) && utils.object.isNull(b)) { return true; } if (utils.object.isNull(a) || utils.object.isNull(b)) { return false; } const aks = this.keys(a); const bks = this.keys(b); const aksl = aks.length; const bksl = bks.length; if (aksl !== bksl) { return false; } for (let i = 0; i < aksl; i += 1) { if (isWeak || isString ? `${a[aks[i]]}` !== `${b[aks[i]]}` : a[aks[i]] !== b[aks[i]]) { return false; } } return true; }, keys(m) { const keys = []; for (const key in m) { if (Object.prototype.hasOwnProperty.call(m, key)) { keys.push(key); } } return keys; }, vals(m) { const l = []; const keys = utils.map.keys(m); for (let i = 0, len = keys.length; i < len; i += 1) { l.push(m[keys[i]]); } return l; } }, // 格式化手机号 隐藏中间数据 formatPhoneNumber(phone) { if (!phone) return ''; return `${String(phone).slice(0, 3)}****${String(phone).slice(-4)}`; }, // 数组转 百分比 numberToPercentage(percentage) { if (percentage == null) return '--'; const num = (Math.round(percentage * 10000) / 100).toFixed(2); return Number(percentage) === 0 ? '0%' : `${Math.abs(num)}%`; }, /** * @param {Array} target 目标数组 * @param {Array} arr 需要查询的数组 * @description 判断要查询的数组是否至少有一个元素包含在目标数组中 */ hasOneOf: (targetarr, arr) => { return targetarr.some((_) => arr.indexOf(_) > -1); }, onMsg: (callback) => { window.onmessage = (res) => { callback(res); }; }, /** * 快捷键注册 * @param kes * @param fun */ compositeKey: (kes, fun) => { const k = kes || ''; const fn = fun || function () { }; const ks = k.split('+'); if (ks.length < 2) { console.info('not composite key'); return; } document.addEventListener('keydown', function (e) { const ctrl = e.ctrlKey, shift = e.shiftKey, alt = e.altKey; // @ts-ignore let keyIdent = e.keyIdentifier; if (ctrl && (ks.indexOf('ctrl') === -1)) { return; } if (shift && (ks.indexOf('shift') === -1)) { return; } if (alt && (ks.indexOf('alt') === -1)) { return; } if (e.keyCode > 47 && e.keyCode < 91) { keyIdent = String.fromCharCode(e.keyCode); } if (keyIdent && keyIdent.toLowerCase() === ks[ks.length - 1]) { fn(e); } }); }, /** * 消息通用模板 * @param type primary 主要通知、success 成功通知、warning 警告通知、danger 危险通知 * @param content * @param duration */ message: (type, content, duration = 6) => { // if (mp.isPC()) { // @ts-ignore element_ui_1.default.Message[type]({ message: content, showClose: true, duration: duration * 1000 }); // } else { // if (type == 'error') type = 'danger'; // if (type == 'info') type = 'primary'; // Notify({ // type: type, // message: content, // duration: duration * 1000 // }); // } }, /** * 确认 弹窗通用模板 * @param type * @param title * @param content * @param okCallBack * @param cancelCallBack */ confirm: (type = 'info', title = '', content = '', okCallBack = () => { }, cancelCallBack = () => { }, confirmButtonText = '', cancelButtonText = '') => { // if (mp.isPC()) { element_ui_1.default .MessageBox .confirm(content, title, { confirmButtonText: confirmButtonText, cancelButtonText: cancelButtonText, type: type }) .then(() => { okCallBack(); }) .catch(() => { cancelCallBack(); }); // } else { // // @ts-ignore // Dialog.confirm({ // message: content, title, // confirmButtonText: confirmButtonText, // cancelButtonText: cancelButtonText // }) // .then(() => { // okCallBack(); // }) // .catch(() => { // cancelCallBack(); // }); // } }, /** * 消息 弹窗通用模板 * @param type * @param title * @param content * @param okCallBack * @param cancelCallBack */ alert: (type = 'info', title = '', content = '', okCallBack = () => { }, confirmButtonText = '') => { // if (mp.isPC()) { element_ui_1.default.MessageBox .alert(content, title, { confirmButtonText: confirmButtonText, type: type }) .then(() => { okCallBack(); }); // } else { // // @ts-ignore // Dialog.alert({message: content, title, confirmButtonText: confirmButtonText}) // .then(() => { // okCallBack(); // }); // } }, /** * 通知通用模板 * @param type * @param title * @param message * @param duration */ notice: (type, title, message, duration = 6) => { console.log(type, title, message, duration); // if (mp.isPC()) { // @ts-ignore element_ui_1.default.Notification[type]({ title, message, dangerouslyUseHTMLString: true, duration: duration * 1000 }); // } else { // if (type == 'error') type = 'danger'; // if (type == 'info') type = 'primary'; // // @ts-ignore // Notify({ // type: type, // message: message, // duration: duration * 1000 // }); // } }, /** * 遍历对象 返回 key value * @param obj * @param callback */ forIn: (obj, callback) => { Object.entries(obj).forEach(entry => { callback(...entry); }); } }; exports.default = utils;