feat:【antd】【mall】 spu 相关公共组件迁移

This commit is contained in:
puhui999
2025-11-24 15:03:20 +08:00
parent c842592d10
commit 390d9d7ca7
6 changed files with 609 additions and 8 deletions

View File

@@ -1,6 +1,8 @@
export * from './property-util';
export { default as SkuList } from './sku-list.vue';
export { default as SkuTableSelect } from './sku-table-select.vue';
export { default as SpuAndSkuList } from './spu-and-sku-list.vue';
export { default as SpuSkuSelect } from './spu-select.vue';
export { default as SpuShowcase } from './spu-showcase.vue';
export { default as SpuTableSelect } from './spu-table-select.vue';
export * from './type';

View File

@@ -0,0 +1,177 @@
<script generic="T extends MallSpuApi.Spu" lang="ts" setup>
import type { RuleConfig, SpuProperty } from './type';
import type { MallSpuApi } from '#/api/mall/product/spu';
import { ref, watch } from 'vue';
import { confirm } from '@vben/common-ui';
import { formatToFraction } from '@vben/utils';
import { Button, Image } from 'ant-design-vue';
import { VxeColumn, VxeTable } from '#/adapter/vxe-table';
import SkuList from './sku-list.vue';
defineOptions({ name: 'PromotionSpuAndSkuList' });
const props = withDefaults(
defineProps<{
deletable?: boolean; // SPU 是否可删除
ruleConfig: RuleConfig[];
spuList: T[];
spuPropertyListP: SpuProperty<T>[];
}>(),
{
deletable: false,
},
);
const emit = defineEmits<{
(e: 'delete', spuId: number): void;
}>();
const spuData = ref<MallSpuApi.Spu[]>([]); // spu 详情数据列表
const skuListRef = ref<InstanceType<typeof SkuList> | undefined>(); // 商品属性列表Ref
const spuPropertyList = ref<SpuProperty<T>[]>([]); // spuId 对应的 sku 的属性列表
const expandRowKeys = ref<string[]>([]); // 控制展开行需要设置 row-key 属性才能使用,该属性为展开行的 keys 数组。
/**
* 获取所有 sku 活动配置
*
* @param extendedAttribute 在 sku 上扩展的属性,例:秒杀活动 sku 扩展属性 productConfig 请参考 seckillActivity.ts
*/
function getSkuConfigs(extendedAttribute: string) {
// 验证 SKU 数据(如果有 ref 的话)
if (skuListRef.value) {
try {
skuListRef.value.validateSku();
} catch (error) {
// 验证失败时抛出错误
throw error;
}
}
const seckillProducts: unknown[] = [];
spuPropertyList.value.forEach((item) => {
item.spuDetail.skus?.forEach((sku) => {
const extendedValue = (sku as Record<string, unknown>)[extendedAttribute];
if (extendedValue) {
seckillProducts.push(extendedValue);
}
});
});
return seckillProducts;
}
// 暴露出给表单提交时使用
defineExpose({ getSkuConfigs });
/** 多选时可以删除 SPU */
async function deleteSpu(spuId: number) {
await confirm(`是否删除商品编号为${spuId}的数据?`);
const index = spuData.value.findIndex((item) => item.id === spuId);
if (index !== -1) {
spuData.value.splice(index, 1);
emit('delete', spuId);
}
}
/**
* 将传进来的值赋值给 spuData
*/
watch(
() => props.spuList,
(data) => {
if (!data) return;
spuData.value = data as MallSpuApi.Spu[];
},
{
deep: true,
immediate: true,
},
);
/**
* 将传进来的值赋值给 spuPropertyList
*/
watch(
() => props.spuPropertyListP,
(data) => {
if (!data) return;
spuPropertyList.value = data as SpuProperty<T>[];
// 解决如果之前选择的是单规格 spu 的话后面选择多规格 sku 多规格属性信息不展示的问题。解决方法:让 SkuList 组件重新渲染(行折叠会干掉包含的组件展开时会重新加载)
setTimeout(() => {
expandRowKeys.value = data.map((item) => String(item.spuId));
}, 200);
},
{
deep: true,
immediate: true,
},
);
</script>
<template>
<VxeTable
:data="spuData"
:expand-row-keys="expandRowKeys"
:row-config="{
keyField: 'id',
}"
>
<VxeColumn type="expand" width="30">
<template #content="{ 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>
<slot></slot>
</template>
</SkuList>
</template>
</VxeColumn>
<VxeColumn field="id" align="center" title="商品编号" />
<VxeColumn title="商品图" min-width="80">
<template #default="{ row }">
<Image
v-if="row.picUrl"
:src="row.picUrl"
class="h-[30px] w-[30px] cursor-pointer"
:preview="true"
/>
</template>
</VxeColumn>
<VxeColumn
field="name"
title="商品名称"
min-width="300"
show-overflow="tooltip"
/>
<VxeColumn align="center" title="商品售价" min-width="90">
<template #default="{ row }">
{{ formatToFraction(row.price) }}
</template>
</VxeColumn>
<VxeColumn field="salesCount" align="center" title="销量" min-width="90" />
<VxeColumn field="stock" align="center" title="库存" min-width="90" />
<VxeColumn
v-if="spuData.length > 1 && deletable"
align="center"
title="操作"
min-width="90"
>
<template #default="{ row }">
<Button type="link" danger @click="deleteSpu(row.id)"> 删除</Button>
</template>
</VxeColumn>
</VxeTable>
</template>

View File

@@ -0,0 +1,129 @@
import type { Ref } from 'vue';
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { MallCategoryApi } from '#/api/mall/product/category';
import { computed } from 'vue';
import { formatToFraction } from '@vben/utils';
import { getRangePickerDefaultProps } from '#/utils';
/**
* @description: 列表的搜索表单
*/
export function useGridFormSchema(
categoryTreeList: Ref<MallCategoryApi.Category[]>,
): VbenFormSchema[] {
return [
{
fieldName: 'name',
label: '商品名称',
component: 'Input',
componentProps: {
placeholder: '请输入商品名称',
allowClear: true,
},
},
{
fieldName: 'categoryId',
label: '商品分类',
component: 'TreeSelect',
componentProps: {
treeData: computed(() => categoryTreeList.value),
fieldNames: {
label: 'name',
value: 'id',
},
treeCheckStrictly: true,
placeholder: '请选择商品分类',
allowClear: true,
showSearch: true,
treeNodeFilterProp: 'name',
},
},
{
fieldName: 'createTime',
label: '创建时间',
component: 'RangePicker',
componentProps: {
...getRangePickerDefaultProps(),
allowClear: true,
},
},
];
}
/**
* @description: 列表的字段
*/
export function useGridColumns(
isSelectSku: boolean,
): VxeTableGridOptions['columns'] {
return [
{
type: 'expand',
width: 30,
visible: isSelectSku,
slots: { content: 'expand_content' },
},
{ type: 'checkbox', width: 55 },
{
field: 'id',
title: '商品编号',
minWidth: 100,
align: 'center',
},
{
field: 'picUrl',
title: '商品图',
width: 100,
align: 'center',
cellRender: {
name: 'CellImage',
},
},
{
field: 'name',
title: '商品名称',
minWidth: 300,
showOverflow: 'tooltip',
},
{
field: 'price',
title: '商品售价',
minWidth: 90,
align: 'center',
formatter: ({ cellValue }) => {
// 格式化价格显示(价格以分为单位存储)
return formatToFraction(cellValue);
},
},
{
field: 'salesCount',
title: '销量',
minWidth: 90,
align: 'center',
},
{
field: 'stock',
title: '库存',
minWidth: 90,
align: 'center',
},
{
field: 'sort',
title: '排序',
minWidth: 70,
align: 'center',
},
{
field: 'createTime',
title: '创建时间',
width: 180,
align: 'center',
formatter: 'formatDateTime',
},
] as VxeTableGridOptions['columns'];
}

View File

@@ -0,0 +1,285 @@
<script lang="ts" setup>
import type { PropertyAndValues } from './type';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { MallSpuApi } from '#/api/mall/product/spu';
import { computed, onMounted, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { handleTree } from '@vben/utils';
import { message } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getCategoryList } from '#/api/mall/product/category';
import { getSpu, getSpuPage } from '#/api/mall/product/spu';
import { getPropertyList } from './property-util';
import SkuList from './sku-list.vue';
import { useGridColumns, useGridFormSchema } from './spu-select-data';
defineOptions({ name: 'SpuSelect' });
const props = withDefaults(defineProps<SpuSelectProps>(), {
isSelectSku: false,
radio: false,
});
const emit = defineEmits<{
(e: 'confirm', spuId: number, skuIds?: number[]): void;
}>();
interface SpuSelectProps {
// 默认不需要(不需要的情况下只返回 spu需要的情况下返回 选中的 spu 和 sku 列表)
// 其它活动需要选择商品和商品属性导入此组件即可,需添加组件属性 :isSelectSku='true'
isSelectSku?: boolean; // 是否需要选择 sku 属性
radio?: boolean; // 是否单选 sku
}
// ============ 数据状态 ============
const categoryList = ref<Array<{ id: number; name: string; parentId: number }>>(
[],
); // 分类列表
const categoryTreeList = ref<
Array<{ id: number; name: string; parentId: number }>
>([]); // 分类树
const propertyList = ref<PropertyAndValues[]>([]); // 商品属性列表
const spuData = ref<MallSpuApi.Spu>(); // 当前展开的商品详情
const isExpand = ref(false); // 控制 SKU 列表显示
// ============ 商品选择相关 ============
const selectedSpuId = ref<number>(0); // 选中的商品 spuId
const selectedSkuIds = ref<number[]>([]); // 选中的商品 skuIds
const skuListRef = ref<InstanceType<typeof SkuList>>(); // 商品属性选择 Ref
/** 处理 SKU 选择变化 */
function selectSku(val: MallSpuApi.Sku[]) {
const skuTable = skuListRef.value?.getSkuTableRef();
if (selectedSpuId.value === 0) {
message.warning('请先选择商品再选择相应的规格!!!');
skuTable?.clearSelection();
return;
}
if (val.length === 0) {
selectedSkuIds.value = [];
return;
}
if (props.radio) {
// 只选择一个
selectedSkuIds.value = [val.map((sku) => sku.id!)[0]];
// 如果大于1个
if (val.length > 1) {
// 清空选择
skuTable?.clearSelection();
// 变更为最后一次选择的
skuTable?.toggleRowSelection(val.pop(), true);
}
} else {
selectedSkuIds.value = val.map((sku) => sku.id!);
}
}
/** 处理 SPU 选择变化 */
function selectSpu(val: MallSpuApi.Spu[]) {
if (val.length === 0) {
selectedSpuId.value = 0;
return;
}
// 只选择一个
selectedSpuId.value = val.map((spu) => spu.id!)[0];
// 切换选择 spu 如果有选择的 sku 则清空,确保选择的 sku 是对应的 spu 下面的
if (selectedSkuIds.value.length > 0) {
selectedSkuIds.value = [];
}
// 如果大于1个
if (val.length > 1) {
// 清空选择
gridApi.grid.clearCheckboxRow();
// 变更为最后一次选择的
const lastRow = val.pop();
if (lastRow) {
gridApi.grid.setCheckboxRow(lastRow, true);
}
return;
}
// 自动展开选中的 SPU
if (props.isSelectSku && val[0]) {
expandChange(val[0], [val[0]]);
}
}
/** 处理行展开变化 */
async function expandChange(
row: MallSpuApi.Spu,
expandedRows?: MallSpuApi.Spu[],
) {
// 判断需要展开的 spuId === 选择的 spuId。如果选择了 A 就展开 A 的 skuList。如果选择了 A 手动展开 B 则阻断
// 目的防止误选 sku
if (selectedSpuId.value !== 0) {
if (row.id !== selectedSpuId.value) {
message.warning('你已选择商品请先取消');
// 阻止展开,保持当前选中行的展开状态
await gridApi.grid.setExpandRowKeys([selectedSpuId.value]);
return;
}
// 如果已展开 skuList 则选择此对应的 spu 不需要重新获取渲染 skuList
if (isExpand.value && spuData.value?.id === row.id) {
return;
}
}
spuData.value = undefined;
propertyList.value = [];
isExpand.value = false;
if (expandedRows?.length === 0) {
// 如果展开个数为 0
expandRowKeys.value = [];
return;
}
// 获取 SPU 详情
const res = (await getSpu(row.id as number)) as MallSpuApi.Spu;
// 注意API 返回的价格应该已经是分为单位,无需转换
// 如果 API 返回的是元,则需要转换为分:
res.skus?.forEach((item) => {
if (item.price) item.price = Math.round(item.price * 100);
if (item.marketPrice) item.marketPrice = Math.round(item.marketPrice * 100);
if (item.costPrice) item.costPrice = Math.round(item.costPrice * 100);
if (item.firstBrokeragePrice)
item.firstBrokeragePrice = Math.round(item.firstBrokeragePrice * 100);
if (item.secondBrokeragePrice)
item.secondBrokeragePrice = Math.round(item.secondBrokeragePrice * 100);
});
propertyList.value = getPropertyList(res);
spuData.value = res;
isExpand.value = true;
// 设置展开行(通过 grid API
await gridApi.grid.setExpandRowKeys([row.id!]);
}
/** 确认选择时的触发事件 */
function confirm() {
if (selectedSpuId.value === 0) {
message.warning('没有选择任何商品');
return;
}
if (props.isSelectSku && selectedSkuIds.value.length === 0) {
message.warning('没有选择任何商品属性');
return;
}
// 返回各自 id 列表
props.isSelectSku
? emit('confirm', selectedSpuId.value, selectedSkuIds.value)
: emit('confirm', selectedSpuId.value);
// 关闭弹窗
modalApi.close();
selectedSpuId.value = 0;
selectedSkuIds.value = [];
}
/** 搜索表单 Schema */
const formSchema = computed(() => useGridFormSchema(categoryTreeList));
/** 表格列配置 */
const gridColumns = computed<VxeTableGridOptions['columns']>(() =>
useGridColumns(props.isSelectSku),
);
/** 初始化列表 */
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: formSchema.value,
layout: 'horizontal',
collapsed: false,
},
gridOptions: {
columns: gridColumns.value,
height: 500,
border: true,
checkboxConfig: {
reserve: true,
},
rowConfig: {
keyField: 'id',
isHover: true,
},
expandConfig: props.isSelectSku
? {
trigger: 'row',
reserve: true,
}
: undefined,
proxyConfig: {
ajax: {
async query({ page }: any, formValues: any) {
return await getSpuPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
tabType: 0,
...formValues,
});
},
},
},
},
gridEvents: {
checkboxChange: ({ records }) => {
selectSpu(records as MallSpuApi.Spu[]);
},
expandChange: ({ row, expandedRows }) => {
expandChange(row as MallSpuApi.Spu, expandedRows as MallSpuApi.Spu[]);
},
},
});
/** 初始化弹窗 */
const [Modal, modalApi] = useVbenModal({
destroyOnClose: true,
onConfirm: confirm,
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
await gridApi.grid.clearCheckboxRow();
await gridApi.grid.setExpandRowKeys([]);
selectedSpuId.value = 0;
selectedSkuIds.value = [];
spuData.value = undefined;
propertyList.value = [];
isExpand.value = false;
return;
}
// 打开时查询数据
await gridApi.query();
},
});
/** 对外暴露的方法 */
defineExpose({
open: () => {
modalApi.open();
},
});
/** 初始化分类数据 */
onMounted(async () => {
categoryList.value = await getCategoryList({});
categoryTreeList.value = handleTree(categoryList.value, 'id', 'parentId');
});
</script>
<template>
<Modal title="商品选择" class="w-[70%]">
<Grid>
<!-- 展开列内容SKU 列表 -->
<template v-if="isSelectSku" #expand_content="{ row }">
<SkuList
v-if="isExpand && spuData?.id === row.id"
ref="skuListRef"
:is-component="true"
:is-detail="true"
:prop-form-data="spuData"
:property-list="propertyList"
@selection-change="selectSku"
/>
</template>
</Grid>
</Modal>
</template>

View File

@@ -20,3 +20,9 @@ export interface RuleConfig {
// 校验不通过时的消息提示
message: string;
}
export interface SpuProperty<T> {
propertyList: PropertyAndValues[];
spuDetail: T;
spuId: number;
}

View File

@@ -1,8 +1,9 @@
<script lang="ts" setup>
import type { MallPointActivityApi } from '#/api/mall/promotion/point';
import type { RuleConfig } from '#/views/mall/product/spu/components';
// TODO @puhui999有问题
// import type { SpuProperty } from '#/views/mall/promotion/components/types';
import type {
RuleConfig,
SpuProperty,
} from '#/views/mall/product/spu/components';
import { computed, ref } from 'vue';
@@ -20,10 +21,12 @@ import {
updatePointActivity,
} from '#/api/mall/promotion/point';
import { $t } from '#/locales';
import { getPropertyList } from '#/views/mall/product/spu/components';
import {
getPropertyList,
SpuAndSkuList,
SpuSkuSelect,
} from '#/views/mall/product/spu/components';
// TODO @puhui999有问题
// import { SpuAndSkuList, SpuSkuSelect } from '../../../components';
import { useFormSchema } from '../data';
const emit = defineEmits(['success']);
@@ -72,8 +75,7 @@ const ruleConfig: RuleConfig[] = [
const spuList = ref<any[]>([]); // 选择的 SPU 列表
// TODO @puhui999有问题
// const spuPropertyList = ref<SpuProperty<any>[]>([]); // SPU 属性列表
const spuPropertyList = ref<any[]>([]); // SPU 属性列表
const spuPropertyList = ref<SpuProperty<any>[]>([]); // SPU 属性列表
/** 打开商品选择器 */
// TODO @puhui999spuSkuSelectRef.value.open is not a function