循环遍历数组中的每一项,并根据每一项的某个值进行判断 every 、forEach ,some
项目需求
要求点击某个按钮时,要是都是 已复核 的状态才会请求接口数据,否则不请求并直接给出错误提示。
如下图:
方法一
every()是对数组中每一项运行给定函数,如果该函数对每一项返回true,则返回true。
handleReimbursement = async (selectedRowKeys, rows) => {
const isAllReview = rows.every(row=>row.state === "REVIEW"); // 用every 循环值
if(!isAllReview){ // 判断如果每一个的状态有一个不是 已复核
ElNotification({
type: 'error',
message: '数据报账状态值不统一,请重新选择。'
})
}else{ //每一个的状态都是已复核
const res = await sycaccount(selectedRowKeys)
if (res && res.success) {
ElNotification({
type: 'success',
message: res.msg || '操作成功'
})
this.tableRef.getTableData()
} else {
ElNotification({
type: 'error',
message: res.msg || '操作失败'
})
}
}
}
方法二
forEach循环遍历
handleReimbursement = async (selectedRowKeys, rows) => {
rows.forEach(item => { // 循环遍历返回数组的每一项
if(item.state !== "REVIEW"){ // 判断每一项的状态值 如果不是 已复核
ElNotification({
type: 'error',
message: '数据报账状态值不统一,请重新选择。'
})
return;//在这里 如果有一行不通过 就return 不会走下面的接口了
}
});
const res = await sycaccount(selectedRowKeys)
if (res && res.success) {
ElNotification({
type: 'success',
message: res.msg || '操作成功'
})
this.tableRef.getTableData()
} else {
ElNotification({
type: 'error',
message: res.msg || '操作失败'
})
}
};
some()是对数组中每一项运行给定函数,如果该函数对任一项返回true,则返回true。
handleReapprove = async (rowKeys, rows) => { // 参数 keys ,rows
if (rows.some(item => item.state !== 'APPROVED')) { // 如果有一个值满足状态不是已审批
ElNotification({
type: 'warning',
message: '请选择<状态>为全为【已审批】的单据!'
});
} else {
const res = await review(rowKeys)
this.setState({ passLoading: false, refuseLoading: false })
if (res && res.success) {
ElNotification({
type: 'success',
message: res.msg || '操作成功'
})
this.tableRef.getTableData()
} else {
ElNotification({
type: 'error',
message: res.msg || '操作失败'
})
}
}
}