这篇总结纯粹作为本人在项目中复制的来源,会在代码块中陆续添加方法,也欢迎各位读者朋友将项目开发中常用的函数分享给在下。
1.
// 深拷贝
function cloneObj(obj) {
var newObj = {}
if (obj instanceof Array) {
newObj = []
}
for (var key in obj) {
var val = obj[key]
newObj[key] = typeof val === 'object' ? cloneObj(val) : val
}
return newObj
}
2.
/**
* 将一位数组递归成树 根据id和pid
* @param {*} data 树原始一维数据
* @returns
*/
function generateTree(data) {
let results = []
data.forEach((node) => {
if (!node.parentId) {
results.push({
children: [],
...node
})
}
})
function recursionData(rootArr, sourceArr) {
rootArr.forEach((root) => {
root.children = sourceArr.filter((source) => {
return root.id === source.pId
})
if (root.children.length > 0) {
recursionData(root.children, sourceArr)
}
})
}
recursionData(results, data)
return results
}
3.
/**
* request interceptor 给接口请求添加token
* @param {*} getToken函数为获取token的方法,自行封装
* @returns
*/
axios.interceptors.request.use(
config => {
// 除login接口外其余接口需要将token和userId放到header中
if (getToken()) {
config.headers['Authorization'] = getToken();
// config.headers['userId'] = getUserId();
if (config.method === 'get') {
config.params = Object.assign({}, config.params, {
'_t': new Date().valueOf()
})
}
}
// config.headers['userId'] = 1;
return config;
},
error => {
console.log(error); // for debug
return Promise.reject(error);
}
);
4.
/**
* response interceptor axios接口返回错误处理
* @param {*} Message函数为element-ui的Message模块
* @returns
*/
axios.interceptors.response.use(
/**
* If you want to get http information such as headers or status
* Please return response => response
*/
/**
* Determine the request status by custom code
* Here is just an example
* You can also judge the status by HTTP Status Code
*/
response => {
return response
},
error => {
if (error.response) {
switch (error.response.status) {
case 401:
router.replace({
path: "/login"
// query: { redirect: router.currentRoute.fullPath }
});
break;
case 403:
Message({
type: "error",
message: "暂无权限",
duration: 3000
});
break;
case 500:
if (error.response.data.message) {
Message({
type: "error",
message: error.response.data.message,
duration: 3000
});
} else {
Message({
type: "error",
message: "接口调用失败,服务端有异常!",
duration: 3000
});
}
break;
case 501:
Message({
type: "error",
message: "接口调用失败,服务端有异常!",
duration: 3000
});
break;
case 502:
Message({
type: "error",
message: "网络异常",
duration: 3000
});
break;
case 503:
Message({
type: "error",
message: "网络异常",
duration: 3000
});
break;
}
}
return Promise.reject(error);
}
);
/* 手机号码或者电话号码验证 */
validatephone: (rule, value, callback) => {
let mobile = /^1[3|5|7|8]\d{9}$/
let phone = /^0\d{2,3}-?\d{7,8}$/
let format = mobile.test(value) || phone.test(value)
if (!format) {
callback(new Error('请输入正确号码'))
} else {
callback()
}
},
/*多邮箱,以;分割*/
validateManyMail: (rule, value, cb) => {
let mailReg = /^((([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6}\;))*(([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})))$/
if (!value) {
cb()
} else if (!mailReg.test(value)) {
cb(new Error('邮箱格式不正确'))
} else {
cb()
}
}
/*时间格式*/
export function dateFormat (date) {
const curDate = new Date(date)
const year = curDate.getFullYear()
let month = curDate.getMonth() + 1
let day = curDate.getDate()
const hours = curDate.getHours()
const minute = curDate.getMinutes()
const seconds = curDate.getSeconds()
month = month.toString().length < 2 ? `0${month}` : month
day = day.toString().length < 2 ? `0${day}` : day
return {
year,
month,
day,
hours,
minute,
seconds
}
}
/**
* 判断文件是否是图片
*/
judgeISImage(item) {
var FileExt = item.files[0].fileName.replace(/.+\./, "");
if (['jpg','jpeg','bmp','png','gif'].indexOf(FileExt.toLowerCase()) === -1){
return false;
}else{
return true;
}
}