1、数字转万和千
function setNumbers(max) {
let numbers = ''
if (max >= 10000) {
numbers = `${truncateToOneDecimalPlace(max / 10000)}万`
} else if (max >= 1000) {
numbers = `${truncateToOneDecimalPlace(max / 1000)}千`
} else {
numbers = max
}
return numbers
}2、截取小数点后数字:默认取一位小数
function truncateToOneDecimalPlace(num, digit = 10) {
// 1. 获取原始数值
const originalNum = num
// 2. 将原始数值乘以10
const multipliedNum = originalNum * digit
// 3. 使用Math.floor()函数对乘以10后的结果向下取整
const truncatedNum = Math.floor(multipliedNum)
// 4. 将取整后的结果除以10
const result = truncatedNum / digit
// 5. 返回处理后的数值
return result
}3、深拷贝对象
function deepClone(source) {
if (!source && typeof source !== 'object') {
throw new Error('error arguments', 'deepClone')
}
const targetObj = source.constructor === Array ? [] : {}
Object.keys(source).forEach(keys => {
if (source[keys] && typeof source[keys] === 'object') {
targetObj[keys] = deepClone(source[keys])
} else {
targetObj[keys] = source[keys]
}
})
return targetObj
}4、获取今天的日期
const getToday = function () {
const date = new Date()
const year = date.getFullYear()
let month = date.getMonth() + 1
if (month < 10) {
month = `0${month}`
}
const day = date.getDate()
return `${String(year)}-${month}-${day}`
}5、获取最近一周的日期
type:1、前一周的日期 2、后一周的日期
const reactWeek = (type = 1) => {
const start = new Date()
return type === 1 ? start.getTime() - 3600 * 1000 * 24 * 7 : start.getTime() + 3600 * 1000 * 24 * 7
}6、最近n天的日期(n天之前或n天之后的日期)
days:n天的日期 默认值是30天的日期
type:1、前n天的日期 2、后n天的日期
const react30Day = (days = 30, type = 1) => {
const currentDate = new Date()
currentDate.setDate(type === 1 ? currentDate.getDate() - days : currentDate.getDate() + days)
// 如果需要获取年份、月份和日期的字符串形式:
const year = currentDate.getFullYear()
const month = currentDate.getMonth() + 1 // 月份从0开始,需要加1
const day = currentDate.getDate()
const formattedDate = `${year}-${month}-${day}`
return formattedDate
}7、获取n个月之前的日期或者n个月之后的日期
months:n个月 默认值是3个月
type:1、前n天的日期 2、后n天的日期
const beforeThree = (months = 3, type = 1) => {
const dates = new Date()
dates.setMonth(type === 1 ? dates.getMonth() - months : dates.getMonth() + months)
const pastMonth = dates.getMonth() + 1
const pastDay = dates.getDate()
let pastMonthStr = ''
let pastDayStr = ''
if (pastMonth >= 1 && pastMonth <= 9) {
pastMonthStr = `0${pastMonth}`
} else {
pastMonthStr = `${pastMonth}`
}
if (pastDay >= 0 && pastDay <= 9) {
pastDayStr = `0${pastDay}`
} else {
pastDayStr = `${pastDay}`
}
const endDate = `${dates.getFullYear()}-${pastMonthStr}-${pastDayStr}`
return endDate
}8、获取最近半年的日期
type:1、半年之前的日期 2、半年之后的日期
将半年的时间:365天/2
export const haflYear = (type = 1) => {
// 先获取当前时间
const curDate = new Date().getTime()
// 将半年的时间单位换算成毫秒
const halfYear = (365 / 2) * 24 * 3600 * 1000
// 半年前的时间(毫秒单位)
const pastResult = type === 1 ? curDate - halfYear : curDate + halfYear
// 日期函数,定义起点为半年前
const pastDate = new Date(pastResult)
const pastYear = pastDate.getFullYear()
const pastMonth = pastDate.getMonth() + 1
const pastDay = pastDate.getDate()
let pastMonthStr = ''
let pastDayStr = ''
if (pastMonth >= 1 && pastMonth <= 9) {
pastMonthStr = `0${pastMonth}`
} else {
pastMonthStr = `${pastMonth}`
}
if (pastDay >= 0 && pastDay <= 9) {
pastDayStr = `0${pastDay}`
} else {
pastDayStr = `${pastDay}`
}
const endDate = `${pastYear}-${pastMonthStr}-${pastDayStr}`
return endDate
}9、获取最近一年的日期
type:1、1年之前的日期 2、1年之后的日期
export const reactYear = (type = 1) => {
const nowDate = new Date()
const dates = new Date(nowDate)
dates.setDate(type === 1 ? dates.getDate() - 365 : dates.getDate() + 365)
const seperator1 = '-'
const year = dates.getFullYear()
const month = dates.getMonth() + 1
const strDate = dates.getDate()
let pastMonthStr = ''
let pastDayStr = ''
if (month >= 1 && month <= 9) {
pastMonthStr = `0${month}`
} else {
pastMonthStr = `${month}`
}
if (strDate >= 0 && strDate <= 9) {
pastDayStr = `0${strDate}`
} else {
pastDayStr = `${strDate}`
}
const currentdate = year + seperator1 + pastMonthStr + seperator1 + pastDayStr
return currentdate
}10、过滤富文本中的所有HTML标签
function filterRichText(html) {
// 使用正则表达式去除所有HTML标签
return html.replace(/<[^>]*>/g, '');
}11、下载文件,把二进制流转成文件
方法一:
const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
const URL = window.URL || window.webkitURL
const objectUrl = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = objectUrl // 文件流生成的url
a.download = `个人工作量统计_${this.planDialog.title}批量导出数据`
document.body.appendChild(a)
a.click()
a.remove()方法二:
/**
* 通过文件流下载文件
* @param {*} file 文件流
* @param {*} fileName
* @param {*} fileType
*/
export function downLoadFile(file, fileName = '默认名称', fileType = 'xls') {
const link = document.createElement('a')
const blobUrl = URL.createObjectURL(file)
link.style.display = 'none'
link.href = blobUrl
link.setAttribute('download', `${fileName}.${fileType}`)
document.body.appendChild(link)
link.click()
// 下载完成后移除链接元素并释放 URL 对象
document.body.removeChild(link)
URL.revokeObjectURL(blobUrl)
}12、VUE 校验路由是否存在
export function routeExists(path) {
let hasRoute = false
if (path.indexOf('?') !== -1) {
path = path.slice(0, path.indexOf('?'))
}
const pathArr = path.split('/')
// eslint-disable-next-line array-callback-return
hasRoute = router.options.routes.some(route => {
if (route.children && route.children.length > 0) {
return route.children.some(child => {
return child.path === pathArr[2]
})
} else if (pathArr.length === 2) {
return route.path.indexOf(pathArr[1]) !== -1
}
})
if (hasRoute === false) {
MessageBox.confirm('', '提示', {
showConfirmButton: false,
showCancelButton: false,
customClass: 'noViewingPermission',
type: 'warn'
})
return hasRoute
}
return hasRoute
}
// ===== 当前皙无童看权限样式 start ======
.noViewingPermission {
width: 25rem;
}
.noViewingPermission .el-message-box__content {
width: 100%;
height: 10rem;
background-image: url('~@/assets/404_images/noViewingPermission.png');
background-position: center bottom;
background-repeat: no-repeat;
background-size: contain;
margin-top: 3rem;
}
@media (max-width: 1280px) {
.noViewingPermission {
width: 20rem;
}
.noViewingPermission .el-message-box__content {
height: 8rem;
margin-top: 2rem;
}
}
// ===== 当前皙无童看权限样式 end ======13、获取指定年份的开始日期结束日期
/**
* @description: 获取指定年份的开始日期结束日期
* @param {*} year
* @author: LiSuwan
* @Date: 2024-12-31 11:39:35
*/
export function getYearDateRange(year) {
// 创建开始日期对象,设置为指定年份的第一天(1月1日)
const startDate = new Date(year, 0, 1) // 月份从0开始,0表示1月
console.log(startDate, '开始日期')
// 创建结束日期对象,设置为指定年份的最后一天(12月31日)
// 可以通过设置下一年的第一天,然后减去1毫秒来得到当前年份的最后一天的前一秒(实际上是12月31日23:59:59.999)
const endDate = new Date(year + 1, 0, 0) // 这实际上是下一年的第一天
endDate.setMilliseconds(endDate.getMilliseconds()) // 调整为当前年份的最后时刻
console.log(endDate, '开始日期')
// 返回格式化后的开始日期和结束日期
return {
startDate: formatDate(startDate, 'YYYY-MM-DD'),
endDate: formatDate(endDate, 'YYYY-MM-DD')
}
}14、获取指定年份指定季度的开始日期结束日期
/**
* @description: 获取指定年份指定季度的开始日期结束日期
* @param {*} year
* @param {*} quarter
* @return {*}
* @author: LiSuwan
* @Date: 2024-12-31 14:06:54
*/
export function getQuarterDateRange(year, quarter) {
// 定义季度的开始月份(基于0索引,所以1月对应0,4月对应3,依此类推)
const startMonths = [0, 3, 6, 9]
// 获取季度的开始月份(基于JavaScript的月份索引)
const startMonth = startMonths[quarter]
// 创建开始日期对象(设置为该月的第一天)
const startDate = new Date(year, startMonth, 1)
// 计算季度的结束月份(下一季度的开始月份减1)
const endMonth = startMonths[quarter] + 3
// 注意:这里要处理跨年的情况,但因为我们只关心当前年份,所以结束日期是当前年份该季度的最后一天
// 创建结束日期对象(设置为该月的最后一天)
// 由于JavaScript的Date对象月份是从0开始的,且设置月份为超出范围的值会自动调整到正确的月份和年份,
// 所以我们可以通过设置月份为下一季度的第一个月份,然后日期为0,来得到当前季度的最后一天。
const endDate = new Date(year, endMonth, 0)
// 返回格式化后的开始日期和结束日期(如果需要格式化的话)
return {
startDate: formatDate(startDate, 'YYYY-MM-DD'),
endDate: formatDate(endDate, 'YYYY-MM-DD')
}
}15、获取两个日期之间的天数
/**
* @description:获取两个日期
* @author: LiSuwan
* @Date: 2024-09-24 15:05:16
*/
getDaysBetweenDates(date1, date2) {
// 将日期字符串转换为Date对象
const d1 = new Date(date1)
const d2 = new Date(date2)
// 计算两个日期的时间差(毫秒)
const timeDiff = Math.abs(d2.getTime() - d1.getTime())
// 计算天数
const days = Math.ceil(timeDiff / (1000 * 3600 * 24))
return days + 1
}16、导出excel文件,文件流生成生成文件
exportAll(params, exportUrl, tableRef) {
const crumb = this.$route.matched[1].meta.title
this.tableLoading = true
this.$http({
url: exportUrl,
type: 'get',
responseType: 'blob',
config: {
'content-type': 'application/x-www-form-urlencoded'
},
params
})
.then(res => {
console.log('res', res)
const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
const URL = window.URL || window.webkitURL
const objectUrl = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = objectUrl // 文件流生成的url
a.download = `${crumb}批量导出数据`
document.body.appendChild(a)
a.click()
a.remove()
this.tableLoading = false
this.$refs[tableRef].clearSelection()
this.$message.success('导出成功')
})
.catch(res => {})
}17、VUE获取DOM的尺寸
//获取DOM的尺寸
function getFullDimensions(el) {
const style = window.getComputedStyle(el);
const contentHeight = el.clientHeight; // content + padding
const padding = {
top: parseInt(style.paddingTop),
right: parseInt(style.paddingRight),
bottom: parseInt(style.paddingBottom),
left: parseInt(style.paddingLeft)
};
const margin = {
top: parseInt(style.marginTop),
right: parseInt(style.marginRight),
bottom: parseInt(style.marginBottom),
left: parseInt(style.marginLeft)
};
const border = {
top: parseInt(style.borderTopWidth),
right: parseInt(style.borderRightWidth),
bottom: parseInt(style.borderBottomWidth),
left: parseInt(style.borderLeftWidth)
};
const totalHeight = margin.top + border.top + padding.top + el.offsetHeight + padding.bottom + border.bottom + margin.bottom;
return {
contentHeight, // 内容高度(含padding)
padding, // 四个方向的padding值
margin, // 四个方向的margin值
border, // 四个方向的border宽度
totalHeight // 元素总高度 包含外边距,内边距
};
}18、格式化日期
date:日期
fmt:格式 (YYYY/MM/DD HH:mm)
formatDate = function (date, fmt) {
const time = new Date(date)
const o = {
'M+': time.getMonth() + 1, // 月份
'D+': time.getDate(), // 日
'H+': time.getHours(), // 小时
'm+': time.getMinutes(), // 分
's+': time.getSeconds(), // 秒
'q+': Math.floor((time.getMonth() + 3) / 3), // 季度
S: time.getMilliseconds() // 毫秒
}
if (/(Y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, String(time.getFullYear()).substr(4 - RegExp.$1.length))
}
for (const k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : `00${o[k]}`.substr(String(o[k]).length))
}
}
return fmt
}