|
|
//防抖 延迟执行
export function debounce(fn, delay = 500) { let timer return function() { let args = arguments if (timer) clearTimeout(timer) timer = setTimeout(() => { timer = null fn.apply(this, args) }, delay) } } //节流 首次执行
export function throttle(fn, delay = 1000) { let last = 0 return function() { let now = new Date() if (now - last > delay) { fn.apply(this, arguments) last = now } } } //提示
const toast = (msg, mask = true, icon = 'none', duration = 1500) => { uni.showToast({ title: String(msg), icon: icon, mask: mask, duration: duration, }) } //加载
const loading = (msg = '努力加载中', mask = true) => { uni.showLoading({ title: String(msg), mask: mask, }) } //json参数转url参数
const jsonToUrl = (path, param) => { let url = path let arr = [] if (param) arr = Object.keys(param) if (arr.length && arr.length != 0) { let str = arr.map(key => `${key}=${decodeURIComponent(param[key])}`).join('&') url = `${path}${path ? '?' : ''}${str}` } return url } //url参数转json参数
const urlToJson = (url) => { let path = url let param = {} if (url.indexOf('?') != -1) { path = url.substr(0, url.indexOf('?')) let arr = url.split("?")[1].split("&") arr.forEach(i=>{ if (i.split("=")[1] && i.split("=")[1] != 'undefined') param[i.split("=")[0]] = i.split("=")[1] }) } return { path, param } } //url获取指定参数
const getQuery = (key) => { let query = window.location.search.substring(1); let vars = query.split("&"); for (let i=0;i<vars.length;i++) { let pair = vars[i].split("="); if (pair[0] == key) {return pair[1];} } return(false) } //加法
Number.prototype.add = function(arg) { return (Math.round(this * 100) + Math.round(arg * 100)) / 100 } //减法
Number.prototype.sub = function(arg) { arg = -arg return (Math.round(this * 100) + Math.round(arg * 100)) / 100 } //乘法
Number.prototype.mul = function(arg) { return (Math.round(this * 100) * Math.round(arg * 100)) / 10000 } //除法
Number.prototype.div = function(arg) { let d1, d2, n1, n2 n1 = Number(this.toString().replace(".", "")) n2 = Number(arg.toString().replace(".", "")) try {d1 = this.toString().split(".")[1].length;} catch (e) {d1 = 0;} try {d2 = arg.toString().split(".")[1].length;} catch (e) {d2 = 0;} return toFixed((n1 / n2) * Math.pow(10, d2 - d1), 2) } //四舍五入保留小数
function toFixed(arg, n) { if (n == 0) { return Math.round(arg) } try { var d, carryD, i, ds = arg.toString().split('.'), len = ds[1].length, b0 = '', k = 0 if (len > n) { while(k < n && ds[1].substring(0, ++k) == '0') { b0 += '0' } d = Number(ds[1].substring(0, n)) carryD = Math.round(Number('0.' + ds[1].substring(n, len))) len = (d + carryD).toString().length if (len > n) { return Number(ds[0]) + 1 } else if (len == n) { return Number(ds[0] + '.' + (d + carryD)) } return Number(ds[0] + '.' + b0 + (d + carryD)) } } catch (e) {} return arg } //输出
export default { toast, loading, jsonToUrl, urlToJson, getQuery, }
|