前言
上一章封装了一些常用的正则表达式方法,这章封装数组、对象等方法(如果对正则感兴趣可以查看上一章博客)
根据上一章的方法继续封装更实用的好方法,在我们前端中一个方法好几个地方用,那么你写好几遍就会增加代码体积,那么这期就封装一些实用的好方法,方便我们复用,简化代码
一、创建一个js文件
在我们项目中创建一个js文件方便我们后期调用
我这是在项目中的utils文件中创建一个index.js文件,大家也可以向我一样
二、封装方法
import Cookies from 'js-cookie'
import store from '@/store'
import router from '@/router'
import axios from 'axios'
/**
* 权限
* @param {*} key
*/
export function hasPermission (key) {
return window.SITE_CONFIG['permissions'].indexOf(key) !== -1 || false
}
/**
* 获取字典数据列表
* @param dictType 字典类型
*/
export function getDictDataList (dictType) {
const type = (window.SITE_CONFIG['dictList'] && window.SITE_CONFIG['dictList'].length) ? window.SITE_CONFIG['dictList'].find((element) => (element.dictType === dictType)) : ''
if (type) {
return type.dataList
} else {
return []
}
}
/**
* 获取字典名称
* @param dictType 字典类型
* @param dictValue 字典值
*/
export function getDictLabel (dictType, dictValue, rangeSeparator = ';') {
const type = (window.SITE_CONFIG['dictList'] && window.SITE_CONFIG['dictList'].length) ? window.SITE_CONFIG['dictList'].find((element) => (element.dictType === dictType)) : ''
if (type) {
if (Array.isArray(dictValue)) {
if (dictValue.length) {
const labelData = []
type.dataList.forEach((item) => {
dictValue.forEach((it) => {
if (item.dictValue === it + '') {
labelData.push(item.dictLabel)
}
})
})
return labelData.join(rangeSeparator)
} else {
return ''
}
} else {
const val = type.dataList.find((element) => (element.dictValue === dictValue + ''))
if (val) {
return val.dictLabel
} else {
return dictValue
}
}
} else {
return dictValue
}
}
/**
* 清除登录信息
*/
export function clearLoginInfo () {
store.commit('resetStore')
Cookies.remove('access_token')
window.localStorage.removeItem('deptCode')
window.localStorage.removeItem('deptList')
window.SITE_CONFIG['dynamicMenuRoutesHasAdded'] = false
}
/**
* 获取svg图标(id)列表
*/
export function getIconList () {
var res = []
document.querySelectorAll('svg symbol').forEach(item => {
res.push(item.id)
})
return res
}
/**
* 树形数据转换
* @param {*} data
* @param {*} id
* @param {*} pid
*/
export function treeDataTranslate (data, id = 'id', pid = 'pid') {
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]) {
res.push(data[k])
continue
}
if (!temp[data[k][pid]]['children']) {
temp[data[k][pid]]['children'] = []
}
temp[data[k][pid]]['children'].push(data[k])
data[k]['_level'] = (temp[data[k][pid]]._level || 0) + 1
}
return res
}
/**
* 关闭当前tab
*/
export function closeTab (tabName, toName, toParams) {
console.log(store.state.contentTabs, '111111111111111111')
store.state.contentTabs = store.state.contentTabs.filter(item => item.name !== tabName)
let tab = store.state.contentTabs[store.state.contentTabs.length - 1]
router.push({
name: /^iframe_.+/.test(toName) ? 'iframe' : toName,
params: toParams || { ...tab.params }
// query: { ...tab.query }
})
}
/**
* 关闭当前tab返回上一页
*/
export function reservationCloseTab (tabName, toName, toParams) {
console.log(store.state.contentTabs, '111111111111111111')
store.state.contentTabs = store.state.contentTabs.filter(item => item.name !== tabName)
router.go(-1)
}
// 获取数组中的名称字符串
export function getName (array, label = 'name', rangeSeparator = ';') {
if (array.length) {
return array.map((item) => {
if (item[label]) {
return item[label]
} else {
return ''
}
}).join(rangeSeparator)
} else {
return ''
}
}
/**
* 去除空tree空的children
* @param {*} arr
*/
export function removeTreeEmptyChildren (arr = []) {
arr.forEach((item) => {
if (!item.children.length) {
item.children = null
} else {
removeTreeEmptyChildren(item.children)
}
})
return arr
}
// 获取有几个互不相交的区间
export function intervalSchedule (intvs) {
if (intvs.length === 0) {
return 0
}
const sortArray = intvs.sort((a, b) => a[1] - b[1])
let count = 1
let xEnd = sortArray[0][1]
for (let item of intvs) {
const start = item[0]
if (start > xEnd) {
count++
xEnd = item[1]
}
}
return count
}
// 根据日期获取星期几
export function getWeekday (date) {
const weekArray = ['日', '一', '二', '三', '四', '五', '六']
let week = weekArray[new Date(date).getDay()]
if (week) {
return `星期${week}`
} else {
return ''
}
}
// 获取树形的子级
export function lookForAllId (data = [], arr = []) {
for (let item of data) {
if (item.children && item.children.length) {
lookForAllId(item.children, arr)
} else {
arr.push(item)
}
}
return arr
}
// 根据生日计算年龄
export function getAge (strAge) {
if (!strAge) {
return
}
const birArr = strAge.split('-')
const birYear = Number(birArr[0])
const birMonth = Number(birArr[1])
const birDay = Number(birArr[2])
const today = new Date()
const nowYear = today.getFullYear()
const nowMonth = today.getMonth() + 1 // 记得加1
const nowDay = today.getDate()
let returnAge
if (birArr === null) {
return false
};
const d = new Date(birYear, birMonth - 1, birDay)
if (d.getFullYear() === birYear && (d.getMonth() + 1) === birMonth && d.getDate() === birDay) {
if (nowYear === birYear) {
returnAge = 0 //
} else {
let ageDiff = nowYear - birYear // 获取根据年份的年龄
if (ageDiff > 0) {
if (nowMonth === birMonth) {
let dayDiff = nowDay - birDay // 获取几号
if (dayDiff < 0) {
returnAge = ageDiff - 1
} else {
returnAge = ageDiff
}
} else {
let monthDiff = nowMonth - birMonth // 获取月份
if (monthDiff < 0) {
returnAge = ageDiff - 1
} else {
returnAge = ageDiff
}
}
} else {
return '' // 返回-1 表示出生日期输入错误 晚于今天
}
}
return returnAge
} else {
return ''
}
}
// a 链接下载
export function downloadFile (url, filename) {
if (!url) {
return
}
axios({
url,
responseType: 'blob'
}).then(res => {
download(res.data, filename)
}).catch(() => { })
}
// 手机号加密
export function encryptionPhone (phone) {
let reg = /(\d{3})\d{4}(\d{4})/ // 正则表达式
if (phone && phone.length === 11) {
return phone.replace(reg, '$1****$2')
} else {
return phone
}
}
// 图片加载
export function loadImage (url) {
return new Promise((resolve, reject) => {
const image = new window.Image()
image.onload = () => resolve(image)
image.onerror = () => reject(new Error('Could not load image at ' + url))
image.src = url
})
}
// 随机生成唯一字符串
export function uniqueId () {
const timestamp = new Date().getTime()
const random = Math.floor(Math.random() * 1000)
return `${timestamp}_${random}`
}
三、方法使用
这些方法使用跟上一章正则方法使用是一样的,大家可以结合上一章进行使用
总结
感谢大家的观看,博主会后期更新更好的方法,喜欢的话可以关注博主哦~
谢谢