fix: 封装 SpuSelect SpuAndSkuList 为商品活动商品选择商品编辑通用组件

This commit is contained in:
puhui999
2023-06-25 16:43:49 +08:00
parent 76ccc54a35
commit 51e79f29cc
12 changed files with 229 additions and 177 deletions

View File

@@ -8,10 +8,15 @@
:schema="allSchemas.formSchema"
>
<!-- 先选择 -->
<template #spuId>
<el-button @click="spuAndSkuSelectForm.open('秒杀商品选择')">选择商品</el-button>
<template #spuIds>
<el-button @click="spuSelectRef.open()">选择商品</el-button>
<!-- TODO @puhui999默认展开 SKU 毕竟 SKU 是主角SPU 是配角 -->
<SpuAndSkuList ref="spuAndSkuListRef" :spu-list="spuList" />
<SpuAndSkuList
ref="spuAndSkuListRef"
:rule-config="ruleConfig"
:spu-list="spuList"
:spu-property-list-p="spuPropertyList"
/>
</template>
</Form>
<template #footer>
@@ -19,15 +24,15 @@
<el-button @click="dialogVisible = false"> </el-button>
</template>
</Dialog>
<!-- TODO @puhui999这个组件是不是 SpuSelect不需要带 sku 或者 Form -->
<SpuAndSkuSelectForm ref="spuAndSkuSelectForm" @confirm="selectSpu" />
<SpuSelect ref="spuSelectRef" :is-select-sku="true" @confirm="selectSpu" />
</template>
<script lang="ts" setup>
import { SpuAndSkuList, SpuAndSkuSelectForm } from './components'
import { SpuAndSkuList, SpuProperty, SpuSelect } from '../../components'
import { allSchemas, rules } from './seckillActivity.data'
import { Spu } from '@/api/mall/product/spu'
import * as SeckillActivityApi from '@/api/mall/promotion/seckill/seckillActivity'
import { getPropertyList, RuleConfig } from '@/views/mall/product/spu/components'
import * as ProductSpuApi from '@/api/mall/product/spu'
defineOptions({ name: 'PromotionSeckillActivityForm' })
@@ -39,14 +44,26 @@ const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中1修改时的数据加载2提交的按钮禁用
const formType = ref('') // 表单的类型create - 新增update - 修改
const formRef = ref() // 表单 Ref
const spuAndSkuSelectForm = ref() // 商品和属性选择 Ref
const spuSelectRef = ref() // 商品和属性选择 Ref
const spuAndSkuListRef = ref() // sku 秒杀配置组件Ref
const ruleConfig: RuleConfig[] = [
{
name: 'productConfig.stock',
rule: (arg) => arg > 1,
message: '商品秒杀库存必须大于 1 '
},
{
name: 'productConfig.seckillPrice',
rule: (arg) => arg > 0.01,
message: '商品秒杀价格必须大于 0.01 '
}
]
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
dialogVisible.value = true
dialogTitle.value = t('action.' + type)
formType.value = type
resetForm()
// 修改时,设置数据 TODO 没测试估计有问题
if (id) {
formLoading.value = true
@@ -60,12 +77,49 @@ const open = async (type: string, id?: number) => {
}
defineExpose({ open }) // 提供 open 方法,用于打开弹窗
const spuList = ref<Spu[]>([]) // 选择的 spu
const selectSpu = (val: Spu) => {
formRef.value.setValues({ spuId: val.id })
spuList.value = [val]
const spuList = ref<SeckillActivityApi.SpuExtension[]>([]) // 选择的 spu
const spuPropertyList = ref<SpuProperty<SeckillActivityApi.SpuExtension>[]>([])
const selectSpu = (spuIds: number[]) => {
formRef.value.setValues({ spuIds })
getSpuDetails(spuIds)
}
/**
* 获取 SPU 详情
* TODO 获取 SPU 详情,放到各自活动表单来做,让 SpuAndSkuList 职责单一点
* @param spuIds
*/
const getSpuDetails = async (spuIds: number[]) => {
const spuProperties: SpuProperty<SeckillActivityApi.SpuExtension>[] = []
spuList.value = []
// TODO puhui999: 考虑后端添加通过 spuIds 批量获取
for (const spuId of spuIds) {
// 获取 SPU 详情
const res = (await ProductSpuApi.getSpu(spuId)) as SeckillActivityApi.SpuExtension
if (!res) {
continue
}
spuList.value.push(res)
// 初始化每个 sku 秒杀配置
res.skus?.forEach((sku) => {
const config: SeckillActivityApi.SeckillProductVO = {
spuId,
skuId: sku.id!,
stock: 0,
seckillPrice: 0
}
sku.productConfig = config
})
spuProperties.push({ spuId, spuDetail: res, propertyList: getPropertyList(res) })
}
spuPropertyList.value = spuProperties
}
/** 重置表单 */
const resetForm = () => {
spuList.value = []
spuPropertyList.value = []
formRef.value.getElFormRef().resetFields()
}
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件,用于操作成功后的回调
const submitForm = async () => {

View File

@@ -1,163 +0,0 @@
<template>
<el-table :data="spuData">
<el-table-column type="expand" width="30">
<template #default="{ row }">
<SkuList
ref="skuListRef"
:is-activity-component="true"
:prop-form-data="spuPropertyList.find((item) => item.spuId === row.id)?.spuDetail"
:property-list="spuPropertyList.find((item) => item.spuId === row.id)?.propertyList"
:rule-config="ruleConfig"
>
<template #extension>
<el-table-column align="center" label="秒杀库存" min-width="168">
<template #default="{ row: sku }">
<el-input-number v-model="sku.productConfig.stock" :min="0" class="w-100%" />
</template>
</el-table-column>
<el-table-column align="center" label="秒杀价格()" min-width="168">
<template #default="{ row: sku }">
<el-input-number
v-model="sku.productConfig.seckillPrice"
:min="0"
:precision="2"
:step="0.1"
class="w-100%"
/>
</template>
</el-table-column>
</template>
</SkuList>
</template>
</el-table-column>
<el-table-column key="id" align="center" label="商品编号" prop="id" />
<el-table-column label="商品图" min-width="80">
<template #default="{ row }">
<el-image :src="row.picUrl" class="w-30px h-30px" @click="imagePreview(row.picUrl)" />
</template>
</el-table-column>
<el-table-column :show-overflow-tooltip="true" label="商品名称" min-width="300" prop="name" />
<el-table-column align="center" label="商品售价" min-width="90" prop="price">
<template #default="{ row }">
{{ formatToFraction(row.price) }}
</template>
</el-table-column>
<el-table-column align="center" label="销量" min-width="90" prop="salesCount" />
<el-table-column align="center" label="库存" min-width="90" prop="stock" />
</el-table>
</template>
<script lang="ts" setup>
// TODO 后续计划重新封装作为活动商品配置通用组件;可以等其他活动做到的时候,在统一处理 SPU 选择组件哈
import { formatToFraction } from '@/utils'
import { createImageViewer } from '@/components/ImageViewer'
import * as ProductSpuApi from '@/api/mall/product/spu'
import { SpuRespVO } from '@/api/mall/product/spu'
import {
getPropertyList,
Properties,
RuleConfig,
SkuList
} from '@/views/mall/product/spu/components'
import { SeckillProductVO, SpuExtension } from '@/api/mall/promotion/seckill/seckillActivity'
defineOptions({ name: 'PromotionSpuAndSkuList' })
const message = useMessage() // 消息弹窗
// TODO @puhui999是不是改成传递一个 spu 就好啦?
const props = defineProps({
spuList: {
type: Array,
default: () => []
}
})
const spuData = ref<SpuRespVO[]>([]) // spu 详情数据列表
const skuListRef = ref() // 商品属性列表Ref
interface spuProperty {
spuId: number
spuDetail: SpuExtension
propertyList: Properties[]
} // TODO @puhui999类名首字母大写哈
const spuPropertyList = ref<spuProperty[]>([]) // spuId 对应的 sku 的属性列表
/**
* 获取 SPU 详情
* @param spuIds
*/
const getSpuDetails = async (spuIds: number[]) => {
const spuProperties: spuProperty[] = []
// TODO puhui999: 考虑后端添加通过 spuIds 批量获取
for (const spuId of spuIds) {
// 获取 SPU 详情
const res = (await ProductSpuApi.getSpu(spuId)) as SpuExtension
if (!res) {
continue
}
// 初始化每个 sku 秒杀配置
res.skus?.forEach((sku) => {
const config: SeckillProductVO = {
spuId,
skuId: sku.id!,
stock: 0,
seckillPrice: 0
}
sku.productConfig = config
})
spuProperties.push({ spuId, spuDetail: res, propertyList: getPropertyList(res) })
}
spuPropertyList.value = spuProperties
}
const ruleConfig: RuleConfig[] = [
{
name: 'stock',
geValue: 10
},
{
name: 'seckillPrice',
geValue: 0.01
}
]
/**
* 获取所有 sku 秒杀配置
*/
const getSkuConfigs = (): SeckillProductVO[] => {
if (!skuListRef.value.validateSku()) {
// TODO 作为通用组件是需要进一步完善
message.warning('请检查商品相关属性配置!!')
throw new Error('请检查商品相关属性配置!!')
}
const seckillProducts: SeckillProductVO[] = []
spuPropertyList.value.forEach((item) => {
item.spuDetail.skus.forEach((sku) => {
seckillProducts.push(sku.productConfig)
})
})
return seckillProducts
}
// 暴露出给表单提交时使用
defineExpose({ getSkuConfigs })
/** 商品图预览 */
const imagePreview = (imgUrl: string) => {
createImageViewer({
zIndex: 99999999,
urlList: [imgUrl]
})
}
/**
* 将传进来的值赋值给 skuList
*/
watch(
() => props.spuList,
(data) => {
if (!data) return
spuData.value = data as SpuRespVO[]
getSpuDetails(spuData.value.map((spu) => spu.id!))
},
{
deep: true,
immediate: true
}
)
</script>

View File

@@ -1,280 +0,0 @@
<template>
<Dialog v-model="dialogVisible" :appendToBody="true" :title="dialogTitle" width="70%">
<ContentWrap>
<el-row :gutter="20" class="mb-10px">
<el-col :span="6">
<el-input
v-model="queryParams.name"
class="!w-240px"
clearable
placeholder="请输入商品名称"
@keyup.enter="handleQuery"
/>
</el-col>
<el-col :span="6">
<el-tree-select
v-model="queryParams.categoryId"
:data="categoryList"
:props="defaultProps"
check-strictly
class="w-1/1"
node-key="id"
placeholder="请选择商品分类"
@change="nodeClick"
/>
</el-col>
<el-col :span="6">
<el-date-picker
v-model="queryParams.createTime"
:default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
class="!w-240px"
end-placeholder="结束日期"
start-placeholder="开始日期"
type="daterange"
value-format="YYYY-MM-DD HH:mm:ss"
/>
</el-col>
<el-col :span="6">
<el-button @click="handleQuery">
<Icon class="mr-5px" icon="ep:search" />
搜索
</el-button>
<el-button @click="resetQuery">
<Icon class="mr-5px" icon="ep:refresh" />
重置
</el-button>
</el-col>
</el-row>
<el-table
ref="spuListRef"
v-loading="loading"
:data="list"
:expand-row-keys="expandRowKeys"
row-key="id"
@expand-change="expandChange"
@selection-change="selectSpu"
>
<el-table-column v-if="isSelectSku" type="expand" width="30">
<template #default>
<SkuList
v-if="isExpand"
:isComponent="true"
:isDetail="true"
:prop-form-data="spuData"
:property-list="propertyList"
@selection-change="selectSku"
/>
</template>
</el-table-column>
<el-table-column type="selection" width="55" />
<el-table-column key="id" align="center" label="商品编号" prop="id" />
<el-table-column label="商品图" min-width="80">
<template #default="{ row }">
<el-image :src="row.picUrl" class="w-30px h-30px" @click="imagePreview(row.picUrl)" />
</template>
</el-table-column>
<el-table-column
:show-overflow-tooltip="true"
label="商品名称"
min-width="300"
prop="name"
/>
<el-table-column align="center" label="商品售价" min-width="90" prop="price">
<template #default="{ row }">
{{ formatToFraction(row.price) }}
</template>
</el-table-column>
<el-table-column align="center" label="销量" min-width="90" prop="salesCount" />
<el-table-column align="center" label="库存" min-width="90" prop="stock" />
<el-table-column align="center" label="排序" min-width="70" prop="sort" />
<el-table-column
:formatter="dateFormatter"
align="center"
label="创建时间"
prop="createTime"
width="180"
/>
</el-table>
<!-- 分页 -->
<Pagination
v-model:limit="queryParams.pageSize"
v-model:page="queryParams.pageNo"
:total="total"
@pagination="getList"
/>
</ContentWrap>
<template #footer>
<el-button type="primary" @click="confirm"> </el-button>
<el-button @click="dialogVisible = false"> </el-button>
</template>
</Dialog>
</template>
<script lang="ts" setup>
import { getPropertyList, Properties, SkuList } from '@/views/mall/product/spu/components'
import { ElTable } from 'element-plus'
import { dateFormatter } from '@/utils/formatTime'
import { createImageViewer } from '@/components/ImageViewer'
import { formatToFraction } from '@/utils'
import { checkSelectedNode, defaultProps, handleTree } from '@/utils/tree'
import * as ProductCategoryApi from '@/api/mall/product/category'
import * as ProductSpuApi from '@/api/mall/product/spu'
import { propTypes } from '@/utils/propTypes'
defineOptions({ name: 'PromotionSpuAndSkuSelect' })
const props = defineProps({
// 默认不需要(不需要的情况下只返回 spu需要的情况下返回 选中的 spu 和 sku 列表)
// 其它活动需要选择商品和商品属性导入此组件即可,需添加组件属性 :isSelectSku='true'
isSelectSku: propTypes.bool.def(false) // 是否需要选择 sku 属性
})
const message = useMessage() // 消息弹窗
const total = ref(0) // 列表的总页数
const list = ref<any[]>([]) // 列表的数据
const loading = ref(false) // 列表的加载中
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const queryParams = ref({
pageNo: 1,
pageSize: 10,
tabType: 0, // 默认获取上架的商品
name: '',
categoryId: null,
createTime: []
}) // 查询参数
const propertyList = ref<Properties[]>([]) // 商品属性列表
const spuListRef = ref<InstanceType<typeof ElTable>>()
const spuData = ref<ProductSpuApi.Spu | {}>() // 商品详情
const isExpand = ref(false) // 控制 SKU 列表显示
const expandRowKeys = ref<number[]>() // 控制展开行需要设置 row-key 属性才能使用,该属性为展开行的 keys 数组。
// 计算商品属性
const expandChange = async (row: ProductSpuApi.Spu, expandedRows: ProductSpuApi.Spu[]) => {
spuData.value = {}
propertyList.value = []
isExpand.value = false
// 如果展开个数为 0
if (expandedRows.length === 0) {
expandRowKeys.value = []
return
}
// 获取 SPU 详情
const res = (await ProductSpuApi.getSpu(row.id as number)) as ProductSpuApi.SpuRespVO
propertyList.value = getPropertyList(res)
spuData.value = res
isExpand.value = true
expandRowKeys.value = [row.id!]
}
//============ 商品选择相关 ============
const selectedSpu = ref<ProductSpuApi.Spu>() // 选中的商品 spu 只能选择一个
const selectedSku = ref<ProductSpuApi.Sku[]>() // 选中的商品 sku
const selectSku = (val: ProductSpuApi.Sku[]) => {
selectedSku.value = val
}
const selectSpu = (val: ProductSpuApi.Spu[]) => {
// 只选择一个
selectedSpu.value = val[0]
// 如果大于1个
if (val.length > 1) {
// 清空选择
spuListRef.value.clearSelection()
// 变更为最后一次选择的
spuListRef.value.toggleRowSelection(val.pop(), true)
}
}
// 确认选择时的触发事件
const emits = defineEmits<{
(e: 'confirm', value: ProductSpuApi.Spu, value1?: ProductSpuApi.Sku[]): void
}>()
/**
* 确认选择返回选中的 spu 和 sku (如果需要选择sku的话)
*/
const confirm = () => {
if (typeof selectedSpu.value === 'undefined') {
message.warning('没有选择任何商品')
return
}
if (
(props.isSelectSku && typeof selectedSku.value === 'undefined') ||
selectedSku.value?.length === 0
) {
message.warning('没有选择任何商品属性')
return
}
// TODO 返回选择 sku 没测试过,后续测试完善
props.isSelectSku
? emits('confirm', selectedSpu.value!, selectedSku.value!)
: emits('confirm', selectedSpu.value!)
// 关闭弹窗
dialogVisible.value = false
}
// TODO @puhui999直接叫商品选择不用外部传入标题
/** 打开弹窗 TODO 没做国际化 */
const open = (title: string) => {
dialogTitle.value = title
dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法,用于打开弹窗
/** 查询列表 */
const getList = async () => {
loading.value = true
try {
const data = await ProductSpuApi.getSpuPage(queryParams.value)
list.value = data.list
total.value = data.total
} finally {
loading.value = false
}
}
/** 搜索按钮操作 */
const handleQuery = () => {
getList()
}
/** 重置按钮操作 */
const resetQuery = () => {
queryParams.value = {
pageNo: 1,
pageSize: 10,
tabType: 0, // 默认获取上架的商品
name: '',
categoryId: null,
createTime: []
}
getList()
}
/** 商品图预览 */
const imagePreview = (imgUrl: string) => {
createImageViewer({
zIndex: 99999999,
urlList: [imgUrl]
})
}
const categoryList = ref() // 分类树
// TODO @puhui999商品搜索的时候可以通过一级搜二级所以这个校验可以去掉哈也就是说只允许挂在二级但是一级可搜索到
/**
* 校验所选是否为二级及以下节点
*/
const nodeClick = () => {
if (!checkSelectedNode(categoryList.value, queryParams.value.categoryId)) {
queryParams.value.categoryId = null
message.warning('必须选择二级及以下节点!!')
}
}
/** 初始化 **/
onMounted(async () => {
await getList()
// 获得分类树
const data = await ProductCategoryApi.getCategoryList({})
categoryList.value = handleTree(data, 'id', 'parentId')
})
</script>

View File

@@ -1,4 +0,0 @@
import SpuAndSkuSelectForm from './SpuAndSkuSelectForm.vue'
import SpuAndSkuList from './SpuAndSkuList.vue'
export { SpuAndSkuSelectForm, SpuAndSkuList }

View File

@@ -29,6 +29,11 @@
total: tableObject.total
}"
>
<template #configIds="{ row }">
<el-tag v-for="(name, index) in convertSeckillConfigNames(row)" :key="index" class="mr-5px">
{{ name }}
</el-tag>
</template>
<template #action="{ row }">
<el-button
v-hasPermi="['promotion:seckill-activity:update']"
@@ -55,6 +60,7 @@
</template>
<script lang="ts" setup>
import { allSchemas } from './seckillActivity.data'
import { getListAllSimple } from '@/api/mall/promotion/seckill/seckillConfig'
import * as SeckillActivityApi from '@/api/mall/promotion/seckill/seckillActivity'
import SeckillActivityForm from './SeckillActivityForm.vue'
@@ -80,9 +86,16 @@ const openForm = (type: string, id?: number) => {
const handleDelete = (id: number) => {
tableMethods.delList(id, false)
}
const seckillConfigAllSimple = ref([]) // 时段配置精简列表
const convertSeckillConfigNames = computed(
() => (row) =>
seckillConfigAllSimple.value
?.filter((item) => row.configIds.includes(item.id))
?.map((config) => config.name)
)
/** 初始化 **/
onMounted(() => {
getList()
onMounted(async () => {
await getList()
seckillConfigAllSimple.value = await getListAllSimple()
})
</script>

View File

@@ -40,8 +40,7 @@ const crudSchemas = reactive<CrudSchema[]>([
component: 'DatePicker',
componentProps: {
valueFormat: 'YYYY-MM-DD',
type: 'daterange',
defaultTime: [new Date('1 00:00:00'), new Date('1 23:59:59')]
type: 'daterange'
}
},
form: {
@@ -52,7 +51,7 @@ const crudSchemas = reactive<CrudSchema[]>([
}
},
table: {
width: 300
width: 120
}
},
{
@@ -64,8 +63,7 @@ const crudSchemas = reactive<CrudSchema[]>([
component: 'DatePicker',
componentProps: {
valueFormat: 'YYYY-MM-DD',
type: 'daterange',
defaultTime: [new Date('1 00:00:00'), new Date('1 23:59:59')]
type: 'daterange'
}
},
form: {
@@ -76,11 +74,11 @@ const crudSchemas = reactive<CrudSchema[]>([
}
},
table: {
width: 300
width: 120
}
},
{
label: '秒杀时段', // todo @PUHUI999: 在列表界面,格式化不对
label: '秒杀时段',
field: 'configIds',
form: {
component: 'Select',
@@ -106,7 +104,7 @@ const crudSchemas = reactive<CrudSchema[]>([
value: 0
},
table: {
width: 300
width: 120
}
},
{
@@ -118,7 +116,7 @@ const crudSchemas = reactive<CrudSchema[]>([
value: 0
},
table: {
width: 300
width: 120
}
},
{
@@ -130,7 +128,7 @@ const crudSchemas = reactive<CrudSchema[]>([
value: 0
},
table: {
width: 300
width: 120
}
},
{
@@ -141,7 +139,7 @@ const crudSchemas = reactive<CrudSchema[]>([
value: 0
},
table: {
width: 300
width: 120
}
},
{
@@ -152,7 +150,7 @@ const crudSchemas = reactive<CrudSchema[]>([
value: 0
},
table: {
width: 300
width: 120
}
},
{
@@ -164,7 +162,7 @@ const crudSchemas = reactive<CrudSchema[]>([
value: 0
},
table: {
width: 300
width: 120
}
},
{
@@ -175,12 +173,12 @@ const crudSchemas = reactive<CrudSchema[]>([
value: 0
},
table: {
width: 300
width: 120
}
},
{
label: '秒杀活动商品', // TODO @puhui999格式化的商品不对
field: 'spuId',
field: 'spuIds',
form: {
colProps: {
span: 24
@@ -204,7 +202,7 @@ const crudSchemas = reactive<CrudSchema[]>([
},
isForm: false,
table: {
width: 300
width: 120
}
},
{
@@ -215,7 +213,7 @@ const crudSchemas = reactive<CrudSchema[]>([
value: 0
},
table: {
width: 300
width: 80
}
},
{