1. 查询数组首个符合条件数据可以使用find
原代码:
areaChange(e) {
let temp = this.areaOptions.filter(item => item.name === e);
if (temp.length > 0) {
this.formData.area_rel_id = temp[0].id;
} else {
this.formData.area_rel_id = '';
}
},
优化后代码:
areaChange(e) {
this.formData.area_rel_id = this.areaOptions.find(item => item.name === e )?.id || ''
},
2. 三目运算符
源代码:
1.data.approvalStatus === 2 || data.approvalStatus === 4 ? this.showDelete = true : this.showDelete = false//变量赋值(及判断)最好写在前面
2.this.isProcess = row.approvalState == 1 || row.approvalState == 3 ? true : false;
优化后代码:
1.this.showDelete = data.approvalStatus === 2 || data.approvalStatus === 4 ? true :false
2.this.isProcess = row.approvalState == 1 || row.approvalState == 3(row.approvalState == 1 || row.approvalState == 3本身返回就是一个boolean值)
3.多层if的时候要考虑优化
源代码:
//判断是否有推送人力的权限
getButtonPower().then(res => {
if (res.status == 200 && res.data) {
if (res.data.sendRLByOneLevel) {
this.sendRLByOneLevel = true
}
} else{
this.$Message.error(res.message)
}
})
优化后代码:
//判断是否有推送人力的权限
getButtonPower().then(res => {
if (res.status == 200 && res.data) {
this.sendRLByOneLevel = !!res.data.sendRLByOneLevel
} else{
this.$Message.error(res.message)
}
})
4.捕捉错误
可以用try catch:
async getButtonByUserId() {
try {
const res = await getButtonByUserId()
this.btnCodeList = res.data.btnCode.split(',')
this.exportPermission = this.btnCodeList.includes('exportActualControllerCC')
}catch(e) {}
},
只捕获一个错误时:
const res = await getButtonByUserId().catch(err=>{ // 错误处理})
5.判断后返回boolean值,大部分都可以简写
源代码:
if(arr.length>0&&arr.every(item=>item.status!=0)){
return false
}
优化后代码:
return arr.length && arr.some(tiem => item.status == 0)
//arr.every(item=>item.status!=0) 跟 arr.some(tiem => item.status == 0) 同理
6.递归
//搜索 searchFn() { if (this.isEmpty(this.searchInfo)) { this.searchState = false; return; } this.searchState = true; let result = []; this.loopTree(this.treeList, this.searchInfo, result); this.tempList = result; }, /** * 递归模糊匹配数据 * * @param {Array} treeData 树数据 * * @param {String} kewWord 查找的关键词 * * @param {Array} result 查找到的结果 */ loopTree(treeData, keyWord, result) { treeData.forEach(item => { if (item.label.toLowerCase().indexOf(keyWord.toLowerCase()) > -1) { result.push(item); } if (item && item.children && item.children.length > 0) this.loopTree(item.children, keyWord, result); }); },
优化后代码:
searchFn() { let result = this.treeList.filter((item) => myFilter(item, "label", this.searchInfo) ); //先过滤第一层 }, myFilter(arr, key, value) { if (arr.children) { //如果有children再遍历一次 arr.children = arr.children.filter( (item) => this.myFilter(item, key, value) //遍历完递归,判断是否有children ); return arr.children.length; } else { return arr[key].includes(value); } },