UNPKG

tool-class

Version:

this is tools

487 lines (444 loc) 12.4 kB
import dayjs from 'dayjs' import * as Sentry from "@sentry/vue" export const getDateDiff = (dateTimeStamp) => { let second = 1000 let minute = 1000 * 60 let hour = minute * 60 let day = hour * 24 let month = day * 30 let now = new Date().getTime() let diffValue = now - dateTimeStamp if (diffValue < 0) { return '' } let timestampDiff = (now - dateTimeStamp) / second let monthC = parseInt(diffValue / month) let weekC = diffValue / (7 * day) let dayC = diffValue / day let hourC = diffValue / hour let minC = diffValue / minute let today = new Date().getTime() let onData = dayjs(dateTimeStamp).format('YYYY-MM-DD') let todayStr = dayjs(now).format('YYYY-MM-DD') let yesterday = dayjs(today - 24 * 60 * 60 * 1000).format('YYYY-MM-DD') if (onData === todayStr) { return '今天' } if (onData === yesterday) { return '1天前' } if ((monthC >= 1 && monthC < 6)) { return parseInt(monthC) + "月前" } if (monthC >= 6 && monthC < 12) { return "半年前" } if (monthC >= 12) { return "1年前" } if (onData !== yesterday && dayC >= 2 && dayC <= 30) { return parseInt(dayC) + "天前" } if (hourC >= 1 && hourC < 24) { return parseInt(hourC) + "小时前" } if (minC >= 1 && minC < 60) { return parseInt(minC) + "分钟前" } if (timestampDiff < 60) { return "刚刚" } } /** * @params Days 需要获取的天数 * @params timeStamp 当前时间戳 * @params isOld 非0是取当前时间及未来, 0是当前时间和过去时间 */ export const getCustomTime = (Days = 7, timeStamp, isOld = 0) => { let _arr = Array.apply(null, Array(Days)) const distance = 24 * 60 * 60 * 1000 let _target = _arr.map((element, index) => { let _time = !isOld ? (timeStamp - index * distance) : (timeStamp + index * distance) return { date: dayjs(_time).format('MM/DD'), ymd: dayjs(_time).format('YYYY-MM-DD'), week: `星期${isWeek(dayjs(_time).format('dddd'))}`, timeStamp: _time, } }) _target[0].value = '今天' return _target } const isWeek = (val) => { return ({ 'Monday': "一", 'Tuesday': "二", 'Wednesday': "三", 'Thursday': "四", 'Friday': "五", 'Saturday': "六", })[val] || "日" } // 时间转成时间戳 export const timeToTimeStamp = (time = '2019-04-04 14:01:55') => { return new Date(time.replace(new RegExp("-", "gm"), "/")).getTime() } /** * 复制到剪切板 */ export const copyTextToClipboard = async (text = '') => { await navigator.clipboard.writeText(text) } export const stopPropagation = (e) => { e = e || window.event if (e.stopPropagation) { // W3C阻止冒泡方法 e.stopPropagation() } else { e.cancelBubble = true// IE阻止冒泡方法 } } /** * 防抖 */ export const debounce = (fn, wait) => { let timer = null return function () { let context = this, args = arguments if (timer) { clearTimeout(timer) timer = null } timer = setTimeout(() => { fn.apply(context, args) }, wait) } } /** * 节流 */ export const throttle = (fn, delay) => { let curTime = Date.now() return function () { let context = this, args = arguments, nowTime = Date.now() if (nowTime - curTime >= delay) { curTime = Date.now() return fn.apply(context, args) } } } export const exitFullscreen = () => { if (document.exitFullscreen) { document.exitFullscreen() } else if (document.msExitFullscreen) { document.msExitFullscreen() } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen() } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen() } } export const toFullScreen = () => { let element = document.body; if (element.requestFullscreen) { element.requestFullscreen() } else if (element.mozRequestFullScreen) { element.mozRequestFullScreen() } else if (element.msRequestFullscreen) { element.msRequestFullscreen() } else if (element.webkitRequestFullscreen) { element.webkitRequestFullScreen() } } /** * 滚动到指定元素 */ export const smoothScroll = (element) => { document.querySelector(element).scrollIntoView({ behavior: 'smooth' }) } /** * 滚动到页面底部 */ export const scrollToBottom = () => { window.scrollTo(0, document.documentElement.clientHeight) } /** * 滚动到页面顶部 */ export const scrollToTop = () => { const height = document.documentElement.scrollTop || document.body.scrollTop if (height > 0) { window.requestAnimationFrame(scrollToTop) window.scrollTo(0, height - height / 8) } } /** * 判断浏览器型号和版本 */ export const getExplorerInfo = () => { let t = navigator.userAgent.toLowerCase(); return 0 <= t.indexOf("msie") ? { //ie < 11 type: "IE", version: Number(t.match(/msie ([\d]+)/)[1]) } : !!t.match(/trident\/.+?rv:(([\d.]+))/) ? { // ie 11 type: "IE", version: 11 } : 0 <= t.indexOf("edge") ? { type: "Edge", version: Number(t.match(/edge\/([\d]+)/)[1]) } : 0 <= t.indexOf("firefox") ? { type: "Firefox", version: Number(t.match(/firefox\/([\d]+)/)[1]) } : 0 <= t.indexOf("chrome") ? { type: "Chrome", version: Number(t.match(/chrome\/([\d]+)/)[1]) } : 0 <= t.indexOf("opera") ? { type: "Opera", version: Number(t.match(/opera.([\d]+)/)[1]) } : 0 <= t.indexOf("Safari") ? { type: "Safari", version: Number(t.match(/version\/([\d]+)/)[1]) } : { type: t, version: -1 } } /** * 判断window还是mac */ export const osType = () => { const agent = navigator.userAgent.toLowerCase() const isMac = /macintosh|mac os x/i.test(navigator.userAgent) const isWindows = agent.indexOf('win64') >= 0 || agent.indexOf('wow64') >= 0 || agent.indexOf('win32') >= 0 || agent.indexOf('wow32') >= 0 if (isWindows) { return 'windows' } if (isMac) { return 'mac' } } /** * 判断是否安卓设备 */ export const isAndroidMobileDevice = () => { return /android/i.test(navigator.userAgent.toLowerCase()) } /** * 判断是否是苹果还是安卓移动设备 */ export const isAppleMobileDevice = () => { let reg = /iphone|ipod|ipad|Macintosh/i return reg.test(navigator.userAgent.toLowerCase()) } /** * 判断是移动还是PC设备 */ export const isMobile = () => { if ( navigator.userAgent.match( /(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone)/i ) ) { return 'mobile' } return 'desktop' } /** * 键值对拼接成URL参数 */ export const params2Url = (obj) => { let params = [] for (let key in obj) { params.push(`${key}=${obj[key]}`) } return encodeURIComponent(params.join('&')) } /** * 修改URL中的参数 */ export const replaceParamVal = (paramName, replaceWith) => { const oUrl = location.href.toString() const re = eval('/(' + paramName + '=)([^&]*)/gi') location.href = oUrl.replace(re, paramName + '=' + replaceWith) return location.href } /** * 删除URL中指定参数 */ export const funcUrlDel = (name) => { const baseUrl = location.origin + location.pathname + "?" const query = location.search.substr(1) if (query.indexOf(name) > -1) { const obj = {}; const arr = query.split("&") for (let i = 0; i < arr.length; i++) { arr[i] = arr[i].split("=") obj[arr[i][0]] = arr[i][1] } delete obj[name]; return baseUrl + JSON.stringify(obj).replace(/[\"\{\}]/g, "").replace(/\:/g, "=").replace(/\,/g, "&") } } /** * 短横线命名转换成驼峰命名 */ export const getCamelCase = (str) => { return str.replace(/-([a-z])/g, (i, item) => item.toUpperCase()) } /** * 手机号中间四位变成* telFormat */ export const telFormat = (tel) => { tel = String(tel) return tel.substr(0, 3) + "****" + tel.substr(7) } /** * 将RGB转化为十六机制* * @params rgbToHex(255, 255, 255) */ export const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); /** * 数组对象拆分(应用于轮播等) * @params list //需要拆分的数组 * @params num //每行显示个数 */ export const arrayGroups = (list = [], num = 3) => { return list.reduce((map, item, index) => { let page = parseInt(index / num); //3是每一个列需要的个数 if (!map[page]) { map[page] = []; } map[page].push(item); return map; }, {}); } /** * 数组拆分成对象 splitArrayToObject * @params lists //需要拆分的数组 * @params keys //['name', 'id'] */ export const splitArrayToObject = (lists = [], keys = ['name', 'id']) => { lists.map((item, index) => { let obj = {} obj[keys[0]] = item; obj[keys[1]] = index; return obj }) } /** * ios软键盘打开页面视图控制 viewportHandler */ export const viewportHandler = (initial = true) => { if (window.visualViewport.offsetTop === 0 && initial) { let ElementTop = document.getElementById('fixedCss') ElementTop.style.top = 0 + "px" // 固定头部 return } let ElementTop = document.getElementById('fixedCss') ElementTop.style.top = window.visualViewport.offsetTop + "px" } /** * 日志上报 logger * @params json //需要上报的内容对象 * @params query //需要上报的请求参数 */ export const logger = (json = {}, query = '') => { let obj = { query, respose: JSON.stringify(json), time: dayjs(new Date().getTime()).format('YYYY-MM-DD HH:mm:ss') } Sentry.captureException(JSON.stringify(obj)) } /** * 文本中查询所有网址并加上超链接 getLinkContent * @params originalContent //需要提取超链接的字符串 */ export const getLinkContent = (originalContent) => { const LINK_REG = /([--:\w?@%&+~#=]*\.[a-z]{2,4}\/{0,2})((?:[?&](?:\w+)=(?:\w+))+|[--:\w?@%&+~#=]+)?/g const PROTOCOL_REG = /(http|https):\/\/([\w.]+\/?)\S*/ let hasLink = LINK_REG.exec(originalContent) if (!originalContent || !hasLink) return originalContent return originalContent.replace(LINK_REG, (match) => { let protocol = '' // 没有协议头,添加默认协议头 if (!PROTOCOL_REG.exec(match)) { protocol = 'https://' } return `<a href='${protocol}${match}' target='_blank' class="hyperlink">${match}</a>` }) } /** * 引入js injectScript * @params src //需要引入的js地址 */ export const injectScript = (src) => { const s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = src; const t = document.getElementsByTagName('script')[0]; t.parentNode.insertBefore(s, t); } /** * 深拷贝 deepClone */ export function deepClone(source) { const targetObj = source.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象 for (let keys in source) { // 遍历目标 if (source.hasOwnProperty(keys)) { if (source[keys] && typeof source[keys] === 'object') { // 如果值是对象,就递归一下 targetObj[keys] = source[keys].constructor === Array ? [] : {} targetObj[keys] = deepClone(source[keys]) } else { // 如果不是,就直接赋值 targetObj[keys] = source[keys] } } } return targetObj } /** * 计算两个日期的相隔天数 dayDiff * @params dayDiff(new Date("2021-10-21"), new Date("2022-02-12")) */ export const dayDiff = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000) /** * 求平均数 average * @params average([1,9,18,36]) //16 */ export const average = (arr) => arr.reduce((a, b) => a + b) / arr.length /** * 判断数据类型 */ export const trueTypeOf = (obj) => { return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase(); } /** * 解决Promise有其中任意一个报错后不返回正确结果的问题 let promise1 = new Promise((resolve, reject) => { resolve('p1') }) let promise2 = new Promise((resolve, reject) => { reject('promise2') }) * @params promise array 如:// [promise1,promise2] */ export const PromiseAll = (promise = []) => { return Promise.allSettled(promise).then((values) => values) } /** * try cach过多解决方案 * @params const [err, data] = await awaitWrap(fetchDataA()) */ export const awaitWrap = (promise) => { return promise.then((data) => [null, data]).catch((err) => [err, null]) }