要求实现的功能如上:
代码如下:
实现方法1:
attributeChange(){
const data= this.product.saleFormat //复选框的数组
const dataArr = []
data.forEach((item, index) => {
dataArr[index] = []
item.valueItem.forEach((item2, index2) => {
if (item2.value) {
dataArr[index][dataArr[index].length] = item2
}
})
})
const dataArr2 = dataArr.filter(item => {
return item.length !== 0
})
const filterAaleFormatList = this.filterAaleFormatList(dataArr2)
const skuArr = []
this.product.salesSpecs = []
filterAaleFormatList.forEach((item, index) => {
skuArr[index] = {}
item.forEach((item2, index2) => {
if (item2) {
if (index2 === 0) {
skuArr[index].combination = item2.attributeName
} else {
skuArr[index].combination = skuArr[index].combination + '|' + item2.attributeName
}
}
})
const params = {
compose: '',
price: '',
stock: '',
weight: '',
productNo: '',
barCode: '',
img: undefined,
combination: skuArr[index].combination
}
this.product.salesSpecs.push(params)
})
}
/**
* 销售规格过滤
*/
filterAaleFormatList(data) {
var arr = data
var sarr = [[]]
for (var i = 0; i < arr.length; i++) {
var tarr = []
for (var j = 0; j < sarr.length; j++) {
for (var k = 0; k < arr[i].length; k++) {
tarr.push(sarr[j].concat(arr[i][k]))
}
}
sarr = tarr
}
return sarr
}
方法2:
attributeChange(){
// this.product.salesSpecs // 承载数组
const mainArr = this.product.saleFormat // 销售规格数组
// 提取出所有选中的数据 start
const selectedArr = [] // 所有选中的数据
mainArr.forEach(item => {
const tempArr = []
item.valueItem.forEach(subItem => {
if (subItem.value) {
tempArr.push(subItem)
}
})
if (tempArr.length) {
selectedArr.push(tempArr)
}
})
// 提取出所有选中的数据 end
const ids = []
const names = []
if (selectedArr.length <= 0) {
for (let i = this.product.salesSpecs.length - 1; i >= 0; i--) {
if (
!names.find(names => names === this.product.salesSpecs[i].combination)
) {
this.uploadAttrImg.splice(i, 1)
this.product.salesSpecs.splice(i, 1)
}
}
return
}
if (selectedArr.length === 1) {
selectedArr[0].forEach(item => {
ids.push(item.id)
names.push(item.attributeName)
})
} else {
const tempList = this.recursion(selectedArr)
tempList.forEach(item => {
const idsArr = []
const namesArr = []
item.forEach(subItem => {
idsArr.push(subItem.id)
namesArr.push(subItem.attributeName)
})
ids.push(idsArr.join(','))
names.push(namesArr.join('|'))
})
}
function getEmptyData(index) {
return {
compose: '',
price: '',
sellingPrice: '',
stock: '',
weight: '',
productNo: '',
barCode: '',
img: ''
}
}
// 剔除新数据中已经没有的老数据
for (let i = this.product.salesSpecs.length - 1; i >= 0; i--) {
if (
!names.find(names => names === this.product.salesSpecs[i].combination)
) {
this.uploadAttrImg.splice(i, 1)
this.product.salesSpecs.splice(i, 1)
}
}
// 遍历新数据,插入老值中还没有的新值
names.forEach((name, index) => {
if (!this.product.salesSpecs.find(item => item.combination === name)) {
const obj = Object.assign(
{ combination: name, ids: ids[index] },
getEmptyData()
)
this.uploadAttrImg.push(this.setUploadInfo(this.product.salesSpecs.length))
this.product.salesSpecs.push(obj)
}
})
return
}
网友评论