save() {
const arr = this.data.fullReduction;
const fullArr = arr.map((item) => Number(item?.full));
const dicountArr = arr.map((item) => Number(item?.discount));
// const isLess = arr.every((item) => Number(item.full) > Number(item.discount));
// const isSortedFull = fullArr.every((item, i) => i === 0 || item > fullArr[i - 1]);
// const isSortedDiscount = dicountArr.every((item, i) => i === 0 || item > dicountArr[i - 1]);
let fullNullIndex = arr.findIndex((item) => item.full === null || item.full === '');
let discountNullIndex = arr.findIndex((item) => item.discount === null || item.discount === '');
let notlessIndex = arr.findIndex((item) => Number(item.full) <= Number(item.discount));
let notSortedFull = fullArr.findIndex((item, i) => (i === 0 || item > fullArr[i - 1]) === false);
let notSortedDiscount = dicountArr.findIndex((item, i) => (i === 0 || item > dicountArr[i - 1]) === false);
console.log('arr', arr);
debugger;
if (fullNullIndex !== -1) {
wx.showToast({
title: `第${notlessIndex + 1}项门槛金额尚未填写`,
icon: 'none',
});
} else if (discountNullIndex !== -1) {
wx.showToast({
title: `第${notlessIndex + 1}项折扣金额尚未填写`,
icon: 'none',
});
} else if (notlessIndex !== -1) {
wx.showToast({
title: `第${notlessIndex + 1}项门槛金额必须大于折扣金额`,
icon: 'none',
});
} else if (notSortedFull !== -1) {
wx.showToast({
title: `门槛金额必须递增(第${notSortedFull + 1}项)`,
icon: 'none',
});
} else if (notSortedDiscount !== -1) {
wx.showToast({
title: `高门槛金额必须大于低门槛折扣金额(第${notSortedDiscount + 1}项)`,
icon: 'none',
});
}
},
优化后:
validate() {
// 校验是否通过,并给出提示信息
// return true or false
const arr = this.data.fullReduction;
const fullArr = arr.map((item) => Number(item?.full));
const dicountArr = arr.map((item) => Number(item?.discount));
const validateConfig = [
{
key: 'fullNullIndex', // 金额尚未填写,
toast: '项门槛金额尚未填写',
fn: () => {
return arr.findIndex((item) => item.full === null || item.full === '');
},
},
{
key: 'discountNullIndex',
toast: '项折扣金额尚未填写',
fn: () => {
return arr.findIndex((item) => item.discount === null || item.discount === '');
},
},
{
key: 'notlessIndex',
toast: '项门槛金额必须大于折扣金额',
fn: () => {
return arr.findIndex((item) => Number(item.full) <= Number(item.discount));
},
},
{
key: 'notSortedFull',
toast: '门槛金额必须递增',
fn: () => {
return fullArr.findIndex((item, i) => (i === 0 || item > fullArr[i - 1]) === false);
},
},
{
key: 'notSortedDiscount',
toast: '高门槛金额必须大于低门槛折扣金额',
fn: () => {
return dicountArr.findIndex((item, i) => (i === 0 || item > dicountArr[i - 1]) === false);
},
},
];
for (let i = 0; i < validateConfig.length; i++) {
const index = validateConfig[i].fn();
if (index !== -1) {
wx.showToast({
title: `第${index + 1}项${validateConfig[i].toast}`,
icon: 'none',
});
return false;
}
}
return true;
},
save() {
const result = this.validate();
},