前言
?最近接了私活,关于器械商城的项目,最后收尾阶段,发现发布商品还是存在着问题,对于多个相同/不同的商品规格输出成商品时,需要依据规格名对规格值进行排列组合,保证所有规格值都可以进行选择。
核心代码部分
数据结构
formState: {
goods: {
goodsSn: '',
...xxx
},
specifications: [
{
specification: '规格',
value: '标准',
picUrl: '',
},
],
products: [
{
specifications: [],
price: 0,
number: 0,
url: '',
},
],
}
转换代码
const specToProduct = () => {
if (state.formState.specifications.length === 0) {
state.formState.products = [];
return;
}
var specValues = [];
var spec = state.formState.specifications[0].specification;
var values = [];
values.push(0);
for (var i = 1; i < state.formState.specifications.length; i++) {
const aspec = state.formState.specifications[i].specification;
if (aspec === spec) {
values.push(i);
} else {
specValues.push(values);
spec = aspec;
values = [];
values.push(i);
}
}
specValues.push(values);
var productsIndex = 0;
var products = [];
var combination = [];
var n = specValues.length;
for (var s = 0; s < n; s++) {
combination[s] = 0;
}
var index = 0;
var isContinue = false;
do {
var specifications= [];
for (var x = 0; x < n; x++) {
var z = specValues[x][combination[x]];
specifications.push(state.formState.specifications[z].value);
}
products[productsIndex] = {
id: productsIndex,
specifications: specifications,
price: 0,
number: 0,
sand: 0,
integral: 0,
url: '',
};
productsIndex++;
index++;
combination[n - 1] = index;
for (var j = n - 1; j >= 0; j--) {
if (combination[j] >= specValues[j].length) {
combination[j] = 0;
index = 0;
if (j - 1 >= 0) {
combination[j - 1] = combination[j - 1] + 1;
}
}
}
isContinue = false;
for (var p = 0; p < n; p++) {
if (combination[p] !== 0) {
isContinue = true;
}
}
} while (isContinue);
state.formState.products = products;
};
?每当我们修改规格时,例如规格的删除/编辑/添加,都需要调用此方法进行重新输出商品。
效果展示
|