element-ui组件库可直接复制
import { Message, MessageBox, Notification } from 'element-ui'
/**
* 获取uuid
*/
export function getUUID () {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
})
}
// 防抖
export const debounce = (fn, interval) => {
var timer
var gapTime = interval || 1000
return function () {
clearTimeout(timer)
var that = this
var args = arguments
timer = setTimeout(function () {
fn.call(that, args)
}, gapTime)
}
}
// 文件下载
export const downloadUrl = (response, text) => {
const blob = new Blob([response.data], {
type: 'application/vnd.ms-excel'
})
if (typeof window.chrome !== 'undefined') {
// chrome
const link = document.createElement('a')
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
if (text) {
link.setAttribute('download', text)
} else {
link.download = decodeURI(
response.headers['content-disposition'].split('filename=').pop()
)
}
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
} else if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE version
window.navigator.msSaveBlob(blob)
} else {
// Firefox version
var file = new File([blob], { type: 'application/force-download' })
window.open(URL.createObjectURL(file))
}
}
// 文件下载 (处理后端返回url字符串类型数据)
export const downloadLinks = (url, text = '下载文件') => {
const iframe = document.createElement('iframe')
iframe.style.display = 'none'
iframe.src = url
document.body.appendChild(iframe)
setTimeout(() => {
iframe.remove()
}, 1000)
}
// 文件下载
export const downloadLink = (url, text='下载文件') => {
const a = document.createElement('a')
fetch(url).then(res => res.blob()).then(blob => {
a.href = URL.createObjectURL(blob)
console.log(a.href)
a.download = text
document.body.appendChild(a)
a.click()
window.URL.revokeObjectURL(a.href);
document.body.removeChild(a);
})
}
/**
* 时间格式化
* @param {*} timestamp
* @returns
*/
export function transformTime (timestamp) {
function addZero (m) {
return m < 10 ? '0' + m : m
}
if (timestamp) {
var time = new Date(timestamp)
var y = time.getFullYear()
var M = time.getMonth() + 1
var d = time.getDate()
var h = time.getHours()
var m = time.getMinutes()
var s = time.getSeconds()
return y + '-' + addZero(M) + '-' + addZero(d) + ' ' + addZero(h) + ':' + addZero(m) + ':' + addZero(s)
} else {
return ''
}
}
/**
* 消息确认框
* @param {*} msg
* @param {*} type success/warning/info/error
* @param {*} okCallback
* @param {*} errCallback
*/
export const openConfirm = (msg, type, okCallback, errCallback) => {
MessageBox.confirm(msg, '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: type
}).then(() => {
// eslint-disable-next-line standard/no-callback-literal
okCallback()
}).catch(() => {
// eslint-disable-next-line standard/no-callback-literal
errCallback()
})
}
/**
* copy
* @param {*} text
* @param {*} message
*/
export const copeData = (text, message) => {
const oInput = document.createElement('input')
oInput.value = text
document.body.appendChild(oInput)
oInput.select()
document.execCommand('Copy')
Message({
message: message || '复制成功',
type: 'success'
})
oInput.parentElement.removeChild(oInput)
}
/**
* 水印
* @param {*} str
* @param {*} parentNode
* @param {*} font
* @param {*} textColor
*/
export const addWaterMarker = (str, parentNode, font, textColor) => {
var can = document.createElement('canvas')
parentNode.appendChild(can)
can.width = 400
can.height = 200
can.style.display = 'none'
var cans = can.getContext('2d')
cans.rotate(-20 * Math.PI / 180)
cans.font = font || "16px Microsoft JhengHei"
cans.fillStyle = textColor || "rgba(180, 180, 180, 0.3)"
cans.textAlign = 'left'
cans.textBaseline = 'Middle'
cans.fillText(str, can.width / 3, can.height / 2)
parentNode.style.backgroundImage = "url(" + can.toDataURL("image/png") + ")"
}
export function isIE () {
const bw = window.navigator.userAgent
const compare = (s) => bw.indexOf(s) >= 0
const ie11 = (() => 'ActiveXObject' in window)()
return compare('MSIE') || ie11
}
==================分割线==================
ant-design 组件库可直接复制
import config from './config'
import { Modal } from 'ant-design-vue'
import Cookies from 'js-cookie'
export function timeFix () {
const time = new Date()
const hour = time.getHours()
return hour < 9 ? '早上好' : hour <= 12 ? '上午好' : hour <= 13 ? '中午好' : hour < 18 ? '下午好' : '晚上好'
}
export function isIE () {
const bw = window.navigator.userAgent
const compare = (s) => bw.indexOf(s) >= 0
const ie11 = (() => 'ActiveXObject' in window)()
return compare('MSIE') || ie11
}
export function treeDataTranslate (data, id = 'id', pid = 'parentId') {
var res = []
var temp = {}
for (var i = 0; i < data.length; i++) {
temp[data[i][id]] = data[i]
}
for (var k = 0; k < data.length; k++) {
if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
if (!temp[data[k][pid]]['children']) {
temp[data[k][pid]]['children'] = []
}
if (!temp[data[k][pid]]['_level']) {
temp[data[k][pid]]['_level'] = 1
}
data[k]['_level'] = temp[data[k][pid]]._level + 1
temp[data[k][pid]]['children'].push(data[k])
} else {
res.push(data[k])
}
}
return res
}
export function transformTime (date, fomatType = 'YYYY-mm-dd HH:MM:SS') {
let ret
const valueDate = date ? new Date(date) : new Date()
const opt = {
'Y+': valueDate.getFullYear().toString(), // 年
'm+': (valueDate.getMonth() + 1).toString(), // 月
'd+': valueDate.getDate().toString(), // 日
'H+': valueDate.getHours().toString(), // 时
'M+': valueDate.getMinutes().toString(), // 分
'S+': valueDate.getSeconds().toString() // 秒
}
for (const k in opt) {
ret = new RegExp('(' + k + ')').exec(fomatType)
if (ret) {
fomatType = fomatType.replace(ret[1], (ret[1].length === 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, '0')))
};
};
return fomatType
}
export const privacyHandler = (value, name) => {
if (!value) {
return ''
}
const config = {
姓名: value.slice(0, 1) + '*',
名字: value.slice(0, 1) + '*',
证件号码: value.slice(0, 3) + '**********' + value.slice(-4),
证件号: value.slice(0, 3) + '**********' + value.slice(-4),
手机号码: value.slice(0, 3) + '****' + value.slice(-4),
手机号: value.slice(0, 3) + '****' + value.slice(-4),
电话号: value.slice(0, 3) + '****' + value.slice(-4),
邮箱: value.slice(0, 2) + '***' + value.slice(-4)
}
return config[name] || value
}
export const deepClone = (object) => {
let str
let newobj = object.constructor === Array ? [] : {}
if (typeof object !== 'object') {
return object
} else if (window.JSON) {
str = JSON.stringify(object)
newobj = JSON.parse(str)
} else {
for (const i in object) {
if (object.hasOwnProperty(i)) {
newobj[i] = typeof object[i] === 'object' ? deepClone(object[i]) : object[i]
}
}
}
return newobj
}
export const downloadTemplate = (url) => {
window.location.href =
config.imgUrlCDN + url
}
/**
* @description: excel表浏览器兼容下载
* @param {Blob} response: 文本流
* @param {String} text:导出的标题
*/
export const downloadUrl = (response, text) => {
const blob = new Blob([response.data], {
type: 'application/vnd.ms-excel'
})
console.log('response', response)
const fileName = text
? `${text}${transformTime(new Date(), 'YYYYmmddHHMMSS')}`
: decodeURI(
response.headers['content-disposition']?.split('filename=').pop() ??
`文件下载${transformTime(new Date(), 'YYYYmmddHHMMSS')}`
)
if (typeof window.chrome !== 'undefined') {
const link = document.createElement('a')
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
link.setAttribute('download', fileName)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
} else if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE
window.navigator.msSaveBlob(blob, fileName + '.xls')
} else {
var file = new File([blob], { type: 'application/force-download' })
window.open(URL.createObjectURL(file))
}
}
export const confirm = (fnOk, content, fnErr = () => { }) => {
Modal.confirm({
centered: true,
title: '提示',
content: `您确定要${content}吗?`,
onOk: () => {
fnOk()
},
onCancel () {
fnErr()
}
})
}
export const chineseNumbers = (num) => {
var m = parseInt(num)
var ml = (m.toString()).split('')
var wlist = ['', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千', '万']
var numlist = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
var cmlist = wlist.slice(0, ml.length)
cmlist = cmlist.reverse()
var result = ''
for (var i = 0; i < ml.length; i++) {
result += numlist[ml[i]] + (ml[i] === 0 ? '' : cmlist[i])
}
return result
}
export const debounce = (fn, interval) => {
var timer
var gapTime = interval || 1000
return function () {
clearTimeout(timer)
var that = this
var args = arguments
timer = setTimeout(function () {
fn.call(that, args)
}, gapTime)
}
}
export const throttle = (fn, delay) => {
var timer
return function () {
var _this = this
var args = arguments
if (timer) {
return
}
timer = setTimeout(function () {
fn.apply(_this, args)
timer = null // 在delay后执行完fn之后清空timer,此时timer为假,throttle触发可以进入计时器
}, delay || 1000)
}
}
// 获取token
export function getToken () {
return Cookies.get('xxx_token')
}
/**
* 查找所有父节点
* @param {*} list 树结构数据
* @param {*} key 数据节点id
* @param {*} id 树数据节点id的判断值
* @returns
*/
export function getAllParentArr (list, key, id) {
for (const i in list) {
if (list[i][key] === id) {
return [list[i]]
}
if (list[i].children) {
const node = this.getAllParentArr(list[i].children, key, id)
if (node !== undefined) {
return node.concat(list[i])
}
}
}
}
/**
* 千分位过滤器
* 10000 => "10,000.00" 千分位/补零
* @param {*} num
* @param {*} zeroFill // 是否补零
* @returns
*/
export function toThousandFilter (num, zeroFill = true) {
const toThousandReg = /\B(?=(\d{3})+(?!\d))/g // 千分位正则
const pointBeforeReg = /^-?\d+/g // 小数点前数字
const pointAfterReg = /\.\d+$/g // 小数点后数字
// 四舍五入保留两位小数
const formatFloat = (src, pos) => {
return Math.round(src * (+`1e${pos}`)) * (+`1e${-pos}`)
}
let numToThousand = `${formatFloat(+num || 0, 2)}`
numToThousand = numToThousand.replace(pointBeforeReg, m => m.replace(toThousandReg, ','))
if (zeroFill) {
if (pointAfterReg.test(numToThousand)) {
numToThousand = numToThousand.replace(pointAfterReg, m => `${m}00`.slice(0, 3))
} else {
numToThousand = `${numToThousand}.00`
}
}
return numToThousand
}
export function Assignment (init, data) {
for (const i in data) {
for (const k in init) {
if (i === k) {
init[i] = data[k]
}
}
}
return init
}
递归树形图转换