code review 商品管理的实现

This commit is contained in:
YunaiV
2023-05-06 22:54:41 +08:00
parent 4a965b8c14
commit e92361ed40
13 changed files with 108 additions and 48 deletions

View File

@@ -0,0 +1,238 @@
<template>
<el-form ref="ProductManagementBasicInfoRef" :model="formData" :rules="rules" label-width="120px">
<el-row>
<el-col :span="12">
<el-form-item label="商品名称" prop="name">
<el-input v-model="formData.name" placeholder="请输入商品名称" />
</el-form-item>
</el-col>
<el-col :span="12">
<!-- TODO @puhui999只能选根节点 -->
<el-form-item label="商品分类" prop="categoryId">
<el-tree-select
v-model="formData.categoryId"
:data="categoryList"
:props="defaultProps"
check-strictly
node-key="id"
placeholder="请选择商品分类"
class="w-1/1"
/>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="商品关键字" prop="keyword">
<el-input v-model="formData.keyword" placeholder="请输入商品关键字" />
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="单位" prop="unit">
<el-select v-model="formData.unit" placeholder="请选择单位" class="w-1/1">
<el-option
v-for="dict in getIntDictOptions(DICT_TYPE.PRODUCT_UNIT)"
:key="dict.value"
:label="dict.label"
:value="dict.value"
/>
</el-select>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="商品简介" prop="introduction">
<el-input
v-model="formData.introduction"
:rows="3"
placeholder="请输入商品简介"
type="textarea"
/>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="商品封面图" prop="picUrl">
<UploadImg v-model="formData.picUrl" height="80px" />
</el-form-item>
</el-col>
<el-col :span="24">
<el-form-item label="商品轮播图" prop="sliderPicUrls">
<UploadImgs v-model="formData.sliderPicUrls" />
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="运费模板" prop="deliveryTemplateId">
<el-select v-model="formData.deliveryTemplateId" placeholder="请选择" class="w-1/1">
<el-option v-for="item in []" :key="item.id" :label="item.name" :value="item.id" />
</el-select>
</el-form-item>
</el-col>
<el-col :span="12">
<el-button class="ml-20px">运费模板</el-button>
</el-col>
<el-col :span="12">
<el-form-item label="商品规格" props="specType">
<el-radio-group v-model="formData.specType" @change="onChangeSpec">
<el-radio :label="false" class="radio">单规格</el-radio>
<el-radio :label="true">多规格</el-radio>
</el-radio-group>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="分销类型" props="subCommissionType">
<el-radio-group v-model="formData.subCommissionType" @change="changeSubCommissionType">
<el-radio :label="false">默认设置</el-radio>
<el-radio :label="true" class="radio">自行设置</el-radio>
</el-radio-group>
</el-form-item>
</el-col>
<!-- 多规格添加-->
<el-col :span="24">
<el-form-item v-if="formData.specType" label="商品属性">
<!-- TODO @puhui999参考 https://admin.java.crmeb.net/store/list/creatProduct 添加规格好做么添加的时候不用输入备注哈 -->
<el-button class="mr-15px mb-10px" @click="AttributesAddFormRef.open">添加规格</el-button>
<ProductAttributes :attribute-data="attributeList" />
</el-form-item>
<template v-if="formData.specType && attributeList.length > 0">
<el-form-item label="批量设置">
<SkuList :attributeList="attributeList" :is-batch="true" :prop-form-data="formData" />
</el-form-item>
<el-form-item label="属性列表">
<SkuList :attributeList="attributeList" :prop-form-data="formData" />
</el-form-item>
</template>
<el-form-item v-if="!formData.specType">
<SkuList :attributeList="attributeList" :prop-form-data="formData" />
</el-form-item>
</el-col>
</el-row>
</el-form>
<ProductAttributesAddForm ref="AttributesAddFormRef" @success="addAttribute" />
</template>
<script lang="ts" name="ProductManagementBasicInfoForm" setup>
import { PropType } from 'vue'
import { defaultProps, handleTree } from '@/utils/tree'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import type { SpuType } from '@/api/mall/product/management/type/spuType'
import { UploadImg, UploadImgs } from '@/components/UploadFile'
import { copyValueToTarget } from '@/utils/object'
import { ProductAttributes, ProductAttributesAddForm, SkuList } from './index'
import * as ProductCategoryApi from '@/api/mall/product/category'
import { propTypes } from '@/utils/propTypes'
const message = useMessage() // 消息弹窗
const props = defineProps({
propFormData: {
type: Object as PropType<SpuType>,
default: () => {}
},
activeName: propTypes.string.def('')
})
const AttributesAddFormRef = ref() // 添加商品属性表单 TODO @puhui999小写开头哈
const ProductManagementBasicInfoRef = ref() // 表单Ref TODO @puhui999小写开头哈
// TODO @puhui999attributeList 改成 propertyList会更统一一点
const attributeList = ref([]) // 商品属性列表
/** 添加商品属性 */ // TODO @puhui999propFormData 算出来
const addAttribute = (property: any) => {
if (Array.isArray(property)) {
attributeList.value = property
return
}
attributeList.value.push(property)
}
const formData = reactive<SpuType>({
name: '', // 商品名称
categoryId: undefined, // 商品分类
keyword: '', // 关键字
unit: '', // 单位
picUrl: '', // 商品封面图
sliderPicUrls: [], // 商品轮播图
introduction: '', // 商品简介
deliveryTemplateId: 1, // 运费模版
specType: false, // 商品规格
subCommissionType: false, // 分销类型
skus: []
})
const rules = reactive({
name: [required],
categoryId: [required],
keyword: [required],
unit: [required],
introduction: [required],
picUrl: [required],
sliderPicUrls: [required],
// deliveryTemplateId: [required],
specType: [required],
subCommissionType: [required]
})
/**
* 将传进来的值赋值给 formData
*/
watch(
() => props.propFormData,
(data) => {
if (!data) return
copyValueToTarget(formData, data)
},
{
deep: true,
immediate: true
}
)
/**
* 表单校验
*/
const emit = defineEmits(['update:activeName'])
const validate = async () => {
// 校验表单
if (!ProductManagementBasicInfoRef) return
return await unref(ProductManagementBasicInfoRef).validate((valid) => {
if (!valid) {
message.warning('商品信息未完善!!')
emit('update:activeName', 'basicInfo')
// 目的截断之后的校验
throw new Error('商品信息未完善!!')
} else {
// 校验通过更新数据
Object.assign(props.propFormData, formData)
}
})
}
defineExpose({ validate, addAttribute })
/** 分销类型 */
const changeSubCommissionType = () => {
// 默认为零,类型切换后也要重置为零
for (const item of formData.skus) {
item.subCommissionFirstPrice = 0
item.subCommissionSecondPrice = 0
}
}
/** 选择规格 */
const onChangeSpec = () => {
// 重置商品属性列表
attributeList.value = []
// 重置sku列表
formData.skus = [
{
price: 0,
marketPrice: 0,
costPrice: 0,
barCode: '',
picUrl: '',
stock: 0,
weight: 0,
volume: 0,
subCommissionFirstPrice: 0,
subCommissionSecondPrice: 0
}
]
}
const categoryList = ref() // 分类树
onMounted(async () => {
// 获得分类树
const data = await ProductCategoryApi.getCategoryList({})
categoryList.value = handleTree(data, 'id', 'parentId')
})
</script>

View File

@@ -0,0 +1,84 @@
<template>
<el-form ref="DescriptionFormRef" :model="formData" :rules="rules" label-width="120px">
<!--富文本编辑器组件-->
<el-form-item label="商品详情" prop="description">
<Editor v-model:modelValue="formData.description" />
</el-form-item>
</el-form>
</template>
<script lang="ts" name="DescriptionForm" setup>
import type { SpuType } from '@/api/mall/product/management/type/spuType'
import { Editor } from '@/components/Editor'
import { PropType } from 'vue'
import { copyValueToTarget } from '@/utils/object'
import { propTypes } from '@/utils/propTypes'
const message = useMessage() // 消息弹窗
const props = defineProps({
propFormData: {
type: Object as PropType<SpuType>,
default: () => {}
},
activeName: propTypes.string.def('')
})
const DescriptionFormRef = ref() // 表单Ref
const formData = ref<SpuType>({
description: '' // 商品详情
})
// 表单规则
const rules = reactive({
description: [required]
})
/**
* 富文本编辑器如果输入过再清空会有残留,需再重置一次
*/
watch(
() => formData.value.description,
(newValue) => {
if ('<p><br></p>' === newValue) {
formData.value.description = ''
}
},
{
deep: true,
immediate: true
}
)
/**
* 将传进来的值赋值给formData
*/
watch(
() => props.propFormData,
(data) => {
if (!data) return
copyValueToTarget(formData.value, data)
},
{
deep: true,
immediate: true
}
)
/**
* 表单校验
*/
const emit = defineEmits(['update:activeName'])
const validate = async () => {
// 校验表单
if (!DescriptionFormRef) return
return unref(DescriptionFormRef).validate((valid) => {
if (!valid) {
message.warning('商品详情为完善!!')
emit('update:activeName', 'description')
// 目的截断之后的校验
throw new Error('商品详情为完善!!')
} else {
// 校验通过更新数据
Object.assign(props.propFormData, formData.value)
}
})
}
defineExpose({ validate })
</script>

View File

@@ -0,0 +1,156 @@
<template>
<el-form ref="OtherSettingsFormRef" :model="formData" :rules="rules" label-width="120px">
<el-row>
<!-- TODO @puhui999横着三个哈 -->
<el-col :span="24">
<el-col :span="8">
<el-form-item label="商品排序" prop="sort">
<el-input-number v-model="formData.sort" :min="0" />
</el-form-item>
</el-col>
<el-col :span="8">
<el-form-item label="赠送积分" prop="giveIntegral">
<el-input-number v-model="formData.giveIntegral" :min="0" />
</el-form-item>
</el-col>
<el-col :span="8">
<el-form-item label="虚拟销量" prop="virtualSalesCount">
<el-input-number
v-model="formData.virtualSalesCount"
:min="0"
placeholder="请输入虚拟销量"
/>
</el-form-item>
</el-col>
</el-col>
<el-col :span="24">
<el-form-item label="商品推荐">
<el-checkbox-group v-model="checkboxGroup" @change="onChangeGroup">
<el-checkbox v-for="(item, index) in recommend" :key="index" :label="item.value">
{{ item.name }}
</el-checkbox>
</el-checkbox-group>
</el-form-item>
</el-col>
<el-col :span="24">
<!-- TODO tag展示暂时不考虑排序 -->
<el-form-item label="活动优先级">
<el-tag>默认</el-tag>
<el-tag class="ml-2" type="success">秒杀</el-tag>
<el-tag class="ml-2" type="info">砍价</el-tag>
<el-tag class="ml-2" type="warning">拼团</el-tag>
</el-form-item>
</el-col>
<!-- TODO @puhui999等优惠劵 ok 在搞 -->
<el-col :span="24">
<el-form-item label="赠送优惠劵">
<el-button>选择优惠券</el-button>
</el-form-item>
</el-col>
</el-row>
</el-form>
</template>
<script lang="ts" name="OtherSettingsForm" setup>
import type { SpuType } from '@/api/mall/product/management/type/spuType'
import { PropType } from 'vue'
import { copyValueToTarget } from '@/utils/object'
import { propTypes } from '@/utils/propTypes'
const message = useMessage() // 消息弹窗
const props = defineProps({
propFormData: {
type: Object as PropType<SpuType>,
default: () => {}
},
activeName: propTypes.string.def('')
})
// 商品推荐选项 TODO @puhui999这种叫 recommendOptions 会更合适哈
const recommend = [
{ name: '是否热卖', value: 'recommendHot' },
{ name: '是否优惠', value: 'recommendBenefit' },
{ name: '是否精品', value: 'recommendBest' },
{ name: '是否新品', value: 'recommendNew' },
{ name: '是否优品', value: 'recommendGood' }
]
const checkboxGroup = ref<string[]>(['recommendHot']) // 选中推荐选项
/** 选择商品后赋值 */
const onChangeGroup = () => {
// TODO @puhui999是不是可以遍历 recommend然后进行是否选中
checkboxGroup.value.includes('recommendHot')
? (formData.value.recommendHot = true)
: (formData.value.recommendHot = false)
checkboxGroup.value.includes('recommendBenefit')
? (formData.value.recommendBenefit = true)
: (formData.value.recommendBenefit = false)
checkboxGroup.value.includes('recommendBest')
? (formData.value.recommendBest = true)
: (formData.value.recommendBest = false)
checkboxGroup.value.includes('recommendNew')
? (formData.value.recommendNew = true)
: (formData.value.recommendNew = false)
checkboxGroup.value.includes('recommendGood')
? (formData.value.recommendGood = true)
: (formData.value.recommendGood = false)
}
const OtherSettingsFormRef = ref() // 表单Ref
// 表单数据
const formData = ref<SpuType>({
sort: 1, // 商品排序
giveIntegral: 1, // 赠送积分
virtualSalesCount: 1, // 虚拟销量
recommendHot: false, // 是否热卖
recommendBenefit: false, // 是否优惠
recommendBest: false, // 是否精品
recommendNew: false, // 是否新品
recommendGood: false // 是否优品
})
// 表单规则
const rules = reactive({
sort: [required],
giveIntegral: [required],
virtualSalesCount: [required]
})
/**
* 将传进来的值赋值给formData
*/
watch(
() => props.propFormData,
(data) => {
if (!data) return
copyValueToTarget(formData.value, data)
// TODO 如果先修改其他设置的值,再改变商品详情或是商品信息会重置其他设置页面中的相关值 下一个版本修复
checkboxGroup.value = []
formData.value.recommendHot ? checkboxGroup.value.push('recommendHot') : ''
formData.value.recommendBenefit ? checkboxGroup.value.push('recommendBenefit') : ''
formData.value.recommendBest ? checkboxGroup.value.push('recommendBest') : ''
formData.value.recommendNew ? checkboxGroup.value.push('recommendNew') : ''
formData.value.recommendGood ? checkboxGroup.value.push('recommendGood') : ''
},
{
deep: true,
immediate: true
}
)
/**
* 表单校验
*/
const emit = defineEmits(['update:activeName'])
const validate = async () => {
// 校验表单
if (!OtherSettingsFormRef) return
return await unref(OtherSettingsFormRef).validate((valid) => {
if (!valid) {
message.warning('商品其他设置未完善!!')
emit('update:activeName', 'otherSettings')
// 目的截断之后的校验
throw new Error('商品其他设置未完善!!')
} else {
// 校验通过更新数据
Object.assign(props.propFormData, formData.value)
}
})
}
defineExpose({ validate })
</script>

View File

@@ -0,0 +1,102 @@
<template>
<el-col v-for="(item, index) in attributeList" :key="index">
<div>
<el-text class="mx-1">属性名</el-text>
<el-text class="mx-1">{{ item.name }}</el-text>
</div>
<div>
<el-text class="mx-1">属性值</el-text>
<el-tag
v-for="(value, valueIndex) in item.values"
:key="value.id"
:disable-transitions="false"
class="mx-1"
closable
@close="handleClose(index, valueIndex)"
>
{{ value.name }}
</el-tag>
<el-input
v-show="inputVisible(index)"
ref="InputRef"
v-model="inputValue"
class="!w-20"
size="small"
@blur="handleInputConfirm(index, item.id)"
@keyup.enter="handleInputConfirm(index, item.id)"
/>
<el-button
v-show="!inputVisible(index)"
class="button-new-tag ml-1"
size="small"
@click="showInput(index)"
>
+ 添加
</el-button>
</div>
<el-divider class="my-10px" />
</el-col>
</template>
<script lang="ts" name="ProductAttributes" setup>
import { ElInput } from 'element-plus'
import * as PropertyApi from '@/api/mall/product/property'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const inputValue = ref('') // 输入框值
const attributeIndex = ref<number | null>(null) // 获取焦点时记录当前属性项的index
// 输入框显隐控制
const inputVisible = computed(() => (index) => {
if (attributeIndex.value === null) return false
if (attributeIndex.value === index) return true
})
const InputRef = ref() //标签输入框Ref
const attributeList = ref([]) // 商品属性列表
const props = defineProps({
attributeData: {
type: Array,
default: () => {}
}
})
watch(
() => props.attributeData,
(data) => {
if (!data) return
attributeList.value = data
},
{
deep: true,
immediate: true
}
)
/** 删除标签 tagValue 标签值*/
const handleClose = (index, valueIndex) => {
attributeList.value[index].values?.splice(valueIndex, 1)
}
/** 显示输入框并获取焦点 */
const showInput = async (index) => {
attributeIndex.value = index
// 因为组件在ref中所以需要用索引获取对应的Ref
InputRef.value[index]!.input!.focus()
}
/** 输入框失去焦点或点击回车时触发 */
const handleInputConfirm = async (index, propertyId) => {
if (inputValue.value) {
// 保存属性值
try {
const id = await PropertyApi.createPropertyValue({ propertyId, name: inputValue.value })
attributeList.value[index].values.push({ id, name: inputValue.value })
message.success(t('common.createSuccess'))
} catch {
message.error('添加失败,请重试') // TODO 缺少国际化
}
}
attributeIndex.value = null
inputValue.value = ''
}
</script>

View File

@@ -0,0 +1,85 @@
<template>
<Dialog v-model="dialogVisible" :title="dialogTitle">
<el-form
ref="formRef"
v-loading="formLoading"
:model="formData"
:rules="formRules"
label-width="80px"
>
<el-form-item label="名称" prop="name">
<el-input v-model="formData.name" placeholder="请输入名称" />
</el-form-item>
<el-form-item label="备注" prop="remark">
<el-input v-model="formData.remark" placeholder="请输入内容" type="textarea" />
</el-form-item>
</el-form>
<template #footer>
<el-button :disabled="formLoading" type="primary" @click="submitForm"> </el-button>
<el-button @click="dialogVisible = false"> </el-button>
</template>
</Dialog>
</template>
<script lang="ts" name="ProductPropertyForm" setup>
import * as PropertyApi from '@/api/mall/product/property'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('添加商品属性') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中1修改时的数据加载2提交的按钮禁用
const formData = ref({
name: '',
remark: ''
})
const formRules = reactive({
name: [{ required: true, message: '名称不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
/** 打开弹窗 */
const open = async () => {
dialogVisible.value = true
resetForm()
}
defineExpose({ open }) // 提供 open 方法,用于打开弹窗
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件,用于操作成功后的回调
const submitForm = async () => {
// 校验表单
if (!formRef) return
const valid = await formRef.value.validate()
if (!valid) return
// 提交请求
formLoading.value = true
try {
const data = formData.value as PropertyApi.PropertyVO
// 检查属性是否已存在,如果有则返回属性和其下属性值
const res = await PropertyApi.getPropertyListAndValue({ name: data.name })
if (res.length === 0) {
const propertyId = await PropertyApi.createProperty(data)
emit('success', { id: propertyId, ...formData.value, values: [] })
} else {
if (res[0].values === null) {
res[0].values = []
}
emit('success', res[0]) // 因为只用一个
}
message.success(t('common.createSuccess'))
dialogVisible.value = false
} finally {
formLoading.value = false
}
}
/** 重置表单 */
const resetForm = () => {
formData.value = {
name: '',
remark: ''
}
formRef.value?.resetFields()
}
</script>

View File

@@ -0,0 +1,309 @@
<template>
<el-table
:data="isBatch ? SkuData : formData.skus"
border
class="tabNumWidth"
max-height="500"
size="small"
>
<el-table-column align="center" fixed="left" label="图片" min-width="100">
<template #default="{ row }">
<UploadImg v-model="row.picUrl" height="80px" width="100%" />
</template>
</el-table-column>
<template v-if="formData.specType && !isBatch">
<!-- 根据商品属性动态添加 -->
<el-table-column
v-for="(item, index) in tableHeaderList"
:key="index"
:label="item.label"
align="center"
min-width="120"
>
<template #default="{ row }">
{{ row.properties[index]?.valueName }}
</template>
</el-table-column>
</template>
<!-- TODO @puhui999 controls-position="right" 可以去掉哈不然太长了手动输入更方便 -->
<el-table-column align="center" label="商品条码" min-width="168">
<template #default="{ row }">
<el-input v-model="row.barCode" class="w-100%" />
</template>
</el-table-column>
<!-- TODO @puhui999用户输入的时候是按照元分主要是我们自己用 -->
<el-table-column align="center" label="销售价(分)" min-width="168">
<template #default="{ row }">
<el-input-number v-model="row.price" :min="0" class="w-100%" controls-position="right" />
</template>
</el-table-column>
<el-table-column align="center" label="市场价(分)" min-width="168">
<template #default="{ row }">
<el-input-number
v-model="row.marketPrice"
:min="0"
class="w-100%"
controls-position="right"
/>
</template>
</el-table-column>
<el-table-column align="center" label="成本价(分)" min-width="168">
<template #default="{ row }">
<el-input-number
v-model="row.costPrice"
:min="0"
class="w-100%"
controls-position="right"
/>
</template>
</el-table-column>
<el-table-column align="center" label="库存" min-width="168">
<template #default="{ row }">
<el-input-number v-model="row.stock" :min="0" class="w-100%" controls-position="right" />
</template>
</el-table-column>
<el-table-column align="center" label="重量(kg)" min-width="168">
<template #default="{ row }">
<el-input-number v-model="row.weight" :min="0" class="w-100%" controls-position="right" />
</template>
</el-table-column>
<el-table-column align="center" label="体积(m^3)" min-width="168">
<template #default="{ row }">
<el-input-number v-model="row.volume" :min="0" class="w-100%" controls-position="right" />
</template>
</el-table-column>
<template v-if="formData.subCommissionType">
<el-table-column align="center" label="一级返佣(分)" min-width="168">
<template #default="{ row }">
<el-input-number
v-model="row.subCommissionFirstPrice"
:min="0"
class="w-100%"
controls-position="right"
/>
</template>
</el-table-column>
<el-table-column align="center" label="二级返佣(分)" min-width="168">
<template #default="{ row }">
<el-input-number
v-model="row.subCommissionSecondPrice"
:min="0"
class="w-100%"
controls-position="right"
/>
</template>
</el-table-column>
</template>
<el-table-column v-if="formData.specType" align="center" fixed="right" label="操作" width="80">
<template #default>
<el-button v-if="isBatch" link size="small" type="primary" @click="batchAdd">
批量添加
</el-button>
<el-button v-else link size="small" type="primary">删除</el-button>
</template>
</el-table-column>
</el-table>
</template>
<script lang="ts" name="SkuList" setup>
import { UploadImg } from '@/components/UploadFile'
import { PropType } from 'vue'
import { SpuType } from '@/api/mall/product/management/type/spuType'
import { propTypes } from '@/utils/propTypes'
import { SkuType } from '@/api/mall/product/management/type/skuType'
import { copyValueToTarget } from '@/utils/object'
const props = defineProps({
propFormData: {
type: Object as PropType<SpuType>,
default: () => {}
},
attributeList: {
type: Array,
default: () => []
},
isBatch: propTypes.bool.def(false) // 是否批量操作
})
const formData = ref<SpuType>() // 表单数据
// 批量添加时的零时数据 TODO @puhui999小写开头哈然后变量都尾注释
const SkuData = ref<SkuType[]>([
{
/**
* 商品价格,单位:分
*/
price: 0,
/**
* 市场价,单位:分
*/
marketPrice: 0,
/**
* 成本价,单位:分
*/
costPrice: 0,
/**
* 商品条码
*/
barCode: '',
/**
* 图片地址
*/
picUrl: '',
/**
* 库存
*/
stock: 0,
/**
* 商品重量单位kg 千克
*/
weight: 0,
/**
* 商品体积单位m^3 平米
*/
volume: 0,
/**
* 一级分销的佣金,单位:分
*/
subCommissionFirstPrice: 0,
/**
* 二级分销的佣金,单位:分
*/
subCommissionSecondPrice: 0
}
])
/** 批量添加 */
const batchAdd = () => {
formData.value.skus.forEach((item) => {
copyValueToTarget(item, SkuData.value[0])
})
}
const tableHeaderList = ref<{ prop: string; label: string }[]>([])
/**
* 将传进来的值赋值给SkuData
*/
watch(
() => props.propFormData,
(data) => {
if (!data) return
formData.value = data
},
{
deep: true,
immediate: true
}
)
// TODO @芋艿:看看 chatgpt 可以进一步下面几个方法的实现不
/** 生成表数据 */
const generateTableData = (data: any[]) => {
// 构建数据结构
const propertiesItemList = []
for (const item of data) {
const objList = []
for (const v of item.values) {
const obj = { propertyId: 0, valueId: 0, valueName: '' }
obj.propertyId = item.id
obj.valueId = v.id
obj.valueName = v.name
objList.push(obj)
}
propertiesItemList.push(objList)
}
const buildList = build(propertiesItemList)
// 如果构建后的组合数跟sku数量一样的话则不用处理,添加新属性没有属性值也不做处理 (解决编辑表单时或查看详情时数据回显问题)
if (
buildList.length === formData.value.skus.length ||
data.some((item) => item.values.length === 0)
) {
return
}
// 重置表数据
formData.value!.skus = []
buildList.forEach((item) => {
const row = {
properties: [],
price: 0,
marketPrice: 0,
costPrice: 0,
barCode: '',
picUrl: '',
stock: 0,
weight: 0,
volume: 0,
subCommissionFirstPrice: 0,
subCommissionSecondPrice: 0
}
// 判断是否是单一属性的情况
if (Array.isArray(item)) {
row.properties = item
} else {
row.properties.push(item)
}
formData.value.skus.push(row)
})
}
/** 构建所有排列组合 */
const build = (list: any[]) => {
if (list.length === 0) {
return []
} else if (list.length === 1) {
return list[0]
} else {
const result = []
const rest = build(list.slice(1))
for (let i = 0; i < list[0].length; i++) {
for (let j = 0; j < rest.length; j++) {
// 第一次不是数组结构,后面的都是数组结构
if (Array.isArray(rest[j])) {
result.push([list[0][i], ...rest[j]])
} else {
result.push([list[0][i], rest[j]])
}
}
}
return result
}
}
/** 监听属性列表生成相关参数和表头 */
watch(
() => props.attributeList,
(data) => {
// 如果不是多规格则结束
if (!formData.value.specType) return
// 如果当前组件作为批量添加数据使用则重置表数据
if (props.isBatch) {
SkuData.value = [
{
price: 0,
marketPrice: 0,
costPrice: 0,
barCode: '',
picUrl: '',
stock: 0,
weight: 0,
volume: 0,
subCommissionFirstPrice: 0,
subCommissionSecondPrice: 0
}
]
}
// 判断代理对象是否为空
if (JSON.stringify(data) === '[]') return
// 重置表头
tableHeaderList.value = []
// 生成表头
data.forEach((item, index) => {
// name加属性项index区分属性值
tableHeaderList.value.push({ prop: `name${index}`, label: item.name })
})
generateTableData(data)
},
{
deep: true,
immediate: true
}
)
</script>

View File

@@ -0,0 +1,15 @@
import BasicInfoForm from './BasicInfoForm.vue'
import DescriptionForm from './DescriptionForm.vue'
import OtherSettingsForm from './OtherSettingsForm.vue'
import ProductAttributes from './ProductAttributes.vue'
import ProductAttributesAddForm from './ProductAttributesAddForm.vue'
import SkuList from './SkuList.vue'
export {
BasicInfoForm,
DescriptionForm,
OtherSettingsForm,
ProductAttributes,
ProductAttributesAddForm,
SkuList
}