import qs from 'qs'
import router from '@/router'
import cloneDeep from 'lodash/cloneDeep'
import { getToken } from '@/utils/auth'
import { Message } from 'element-ui'
/**
* 通用js方法封装处理
* Copyright (c) 2019 ruoyi
*/
const daasURL = process.env.VUE_APP_DAAS_API
// 日期格式化
export function parseTime (time, pattern) {
if (arguments.length === 0 || !time) {
return null
}
const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
let date
if (typeof time === 'object') {
date = time
} else {
if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
time = parseInt(time)
} else if (typeof time === 'string') {
time = time.replace(new RegExp(/-/gm), '/')
}
if ((typeof time === 'number') && (time.toString().length === 10)) {
time = time * 1000
}
date = new Date(time)
}
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
}
const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
let value = formatObj[key]
// Note: getDay() returns 0 on Sunday
if (key === 'a') {
return ['日', '一', '二', '三', '四', '五', '六'][value]
}
if (result.length > 0 && value < 10) {
value = '0' + value
}
return value || 0
})
return time_str
}
// 表单重置
export function resetForm (refName = 'dataForm') {
if (this.$refs[refName]) {
this.$refs[refName].resetFields()
}
}
// 添加日期范围
export function addDateRange (params, dateRange, dateConfig = { begin: 'beginTime', end: 'endTime' }) {
const search = params
search[dateConfig.begin] = ''
search[dateConfig.end] = ''
if (dateRange !== null && dateRange !== '') {
search[dateConfig.begin] = this.dateRange[0]
search[dateConfig.end] = this.dateRange[1]
}
return search
}
// 回显数据字典
export function selectDictLabel (datas, value) {
var actions = []
Object.keys(datas).map((key) => {
if (datas[key].dictValue === value) {
actions.push(datas[key].dictLabel)
return false
}
})
return actions.join('')
}
// 通用下载方法
export function download (fileName) {
window.location.href = daasURL + '/common/download?fileName=' + encodeURI(fileName) + '&delete=' + true
}
// 字符串格式化(%s )
export function sprintf (str) {
var args = arguments
var flag = true
var i = 1
str = str.replace(/%s/g, function () {
var arg = args[i++]
if (typeof arg === 'undefined') {
flag = false
return ''
}
return arg
})
return flag ? str : ''
}
// 转换字符串,undefined,null等转化为""
export function praseStrEmpty (str) {
if (!str || str === 'undefined' || str === 'null') {
return ''
}
return str
}
/**
* 构造树型结构数据
* @param {*} data 数据源
* @param {*} id id字段 默认 'id'
* @param {*} parentId 父节点字段 默认 'parentId'
* @param {*} children 孩子节点字段 默认 'children'
* @param {*} rootId 根Id 默认 0
*/
export function handleTree (data, id, parentId, children, rootId) {
id = id || 'id'
parentId = parentId || 'parentId'
children = children || 'children'
rootId = rootId || 0
// 对源数据深度克隆
const cloneData = JSON.parse(JSON.stringify(data))
// 循环所有项
const treeData = cloneData.filter(father => {
const branchArr = cloneData.filter(child => {
// 返回每一项的子级数组
return father[id] === child[parentId]
})
branchArr.length > 0 ? father.children = branchArr : ''
// 返回第一层
return father[parentId] === rootId
})
return treeData !== '' ? treeData : data
}
/**
* 字段缺省
* */
export function defaultValue (val, defaultVal = '无') {
return (val === null || val === undefined || val === '') ? defaultVal : val
}
/**
* 导出
* */
export function exportHandle (url, params) {
let paramsStr = qs.stringify(params || {})
window.location.href = `${url}?${paramsStr}&token=${getToken()}`
}
/**
* 获取uuid
*/
export function getUUID (len = 18) {
const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
const uuid = []
const radix = chars.length
for (let i = 0; i < len; i++) {
uuid.push(chars[0 | Math.random() * radix])
}
return uuid.join('')
}
/**
* 转换成金额格式
* */
export function toPrice (money, fixed = 2) {
if (money === null || money === undefined || money === '') {
return '0.00'
}
let n = parseFloat(money).toFixed(fixed)
let re = /(\d{1,3})(?=(\d{3})+(?:\.))/g
return n.replace(re, '$1,')
}
// 千分位转普通数字
export function priceToFloat (money) {
if ((money + '').trim() === '') {
return ''
}
return money.replace(/,/gi, '')
}
// 普通数字转千分位外加.00
export function thousandthFormat (value) {
if (!value && value !== 0) return ''
let str = parseFloat(value).toFixed(2).toString()
let reg =
str.indexOf('.') > -1 ? /(\d)(?=(\d{3})+\.)/g : /(\d)(?=(?:\d{3})+$)/g
return str.replace(reg, '$1,')
}
// 格式化金额
export function formatAmountFunc (val) {
if (typeof val === 'string' && val === '') {
return ''
} else {
if (parseInt(this.priceToFloat(val).toString()).toString().length > 15) {
Message.error('金额输入超出系统支持!!')
return ''
}
const newVal = parseFloat(this.priceToFloat(val).toString() + 'n')
if (isNaN(newVal) || newVal < 0) {
return ''
} else if (newVal >= 0) {
return this.toPrice(newVal)
}
}
}
// 格式化金额
export function formatPrice (price) {
if (typeof price === 'number' && price >= 0) {
return toPrice(price)
} else {
return ''
}
}
/**
* 验证值是否为空
* */
export function isNullOrEmpty (value) {
if (value === null || value === undefined || value === '') {
return true
}
return false
}
// 金额转化不加¥符
export function priceFormat (money, fixed = 2) {
if (money === null || money === undefined || money === '') {
return ''
}
let n = parseFloat(money).toFixed(fixed)
let re = /(\d{1,3})(?=(\d{3})+(?:\.))/g
return n.replace(re, '$1,')
}
/**
* 对象赋值
* */
export function resetObject (targetObj, sourceObj) {
let keys = Object.keys(targetObj)
keys.forEach((key) => {
if (Object.prototype.toString.call(sourceObj) === '[object Object]' && sourceObj[key] !== undefined && sourceObj[key] !== null) {
targetObj[key] = cloneDeep(sourceObj[key])
}
})
return targetObj
}
// 日期格式化
export function dateFormatter (date, fmt) {
if (!(date instanceof Date)) {
return ''
}
fmt = fmt || 'yyyy-MM-dd HH:mm:ss'
var o = {
// 月份
'M+': date.getMonth() + 1,
// 日
'd+': date.getDate(),
// 小时
'H+': date.getHours(),
// 分
'm+': date.getMinutes(),
// 秒
's+': date.getSeconds(),
// 季度
'q+': Math.floor((date.getMonth() + 3) / 3),
// 毫秒
'S': date.getMilliseconds()
}
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
}
for (var k in o) {
if (new RegExp('(' + k + ')').test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
}
}
return fmt
}
/**
* 路由跳转
* s 跳转的路由
* isNew 是否打开新页面
* isReplace 是否覆盖当前路由
* */
export function jumpTo (s, isNew = false, isReplace = false) {
if (!s) {
return false
}
let obj = s
let type = Object.prototype.toString.call(s).match(/\[object\W([a-zA-Z]{1,})/)[1]
if (type === 'String' && s.startsWith('/')) {
obj = {
path: s
}
} else if (type === 'String') {
obj = {
name: s
}
}
if (isNew) {
let routeData = router.resolve(obj)
window.open(routeData.href, '_blank')
} else if (isReplace) {
router.replace(obj)
} else {
router.push(obj)
}
}
/**
* 转换成dictionary下拉数据格式
* */
export function formatToDic (arr, labelId, valueId) {
return arr.map(item => {
return {
label: item[labelId],
value: item[valueId]
}
})
}
/**
* 根据符号转驼峰
* */
export function stringToCamel (str, symbol = '-') {
var temp = str.split(symbol)
for (var i = 1; i < temp.length; i++) {
temp[i] = temp[i][0].toUpperCase() + temp[i].slice(1)
}
return temp.join('')
}
/**
* 数组求和
* */
export function sumArray (arr, key = '') {
if (!key) {
return arr.reduce(function (prev, curr, idx, arr) {
return prev + curr
})
} else {
return arr.map(item => item[key]).reduce(function (prev, curr, idx, arr) {
return prev + curr
})
}
}
前端开发常用工具方法
最新推荐文章于 2024-07-16 17:20:09 发布