style: 优化商品创建和规格编辑模态框样式

This commit is contained in:
ah--desktop
2025-11-04 00:52:08 +08:00
parent ed01f9d391
commit b0a4547e28
4 changed files with 308 additions and 203 deletions
@@ -1,7 +1,8 @@
import { requestClient } from '#/api/request';
import type { ProductDTO, ProductVO } from './types';
import type { PageQueryDTO, PageResultVO } from '#/types/common';
import type { ProductDTO, ProductVO } from './types';
import { requestClient } from '#/api/request';
/**
* 商品管理API
@@ -10,8 +11,13 @@ import type { ProductDTO, ProductVO } from './types';
/**
* 分页获取商品列表
*/
export async function getProductPageApi(params: PageQueryDTO<ProductDTO.Filters>) {
return requestClient.post<PageResultVO<ProductVO.Info>>('/ec/product/page', params);
export async function getProductPageApi(
params: PageQueryDTO<ProductDTO.Filters>,
) {
return requestClient.post<PageResultVO<ProductVO.Info>>(
'/ec/product/page',
params,
);
}
/**
@@ -32,14 +38,7 @@ export async function updateProductApi(id: number, data: ProductDTO.Update) {
* 删除商品
*/
export async function deleteProductApi(id: number) {
return requestClient.delete<void>(`/ec/product/delete/${id}`);
}
/**
* 一键创建商品和规格
*/
export async function createProductWithSpecsApi(data: ProductDTO.CreateWithSpecs) {
return requestClient.post<ProductVO.Info>('/ec/product/create-with-specs', data);
return requestClient.delete(`/ec/product/delete/${id}`);
}
/**
@@ -49,29 +48,43 @@ export async function createProductWithSpecsApi(data: ProductDTO.CreateWithSpecs
/**
* 分页获取商品规格列表
*/
export async function getProductSpecPageApi(params: PageQueryDTO<ProductDTO.SpecFilters>) {
return requestClient.post<PageResultVO<ProductVO.SpecInfo>>('/ec/product-spec/page', params);
export async function getProductSpecPageApi(
params: PageQueryDTO<ProductDTO.SpecFilters>,
) {
return requestClient.post<PageResultVO<ProductVO.SpecInfo>>(
'/ec/product-spec/page',
params,
);
}
/**
* 创建商品规格
*/
export async function createProductSpecApi(data: ProductDTO.CreateSpec) {
return requestClient.post<ProductVO.SpecInfo>('/ec/product-spec/create', data);
return requestClient.post<ProductVO.SpecInfo>(
'/ec/product-spec/create',
data,
);
}
/**
* 更新商品规格
*/
export async function updateProductSpecApi(id: number, data: ProductDTO.UpdateSpec) {
return requestClient.put<ProductVO.SpecInfo>(`/ec/product-spec/update/${id}`, data);
export async function updateProductSpecApi(
id: number,
data: ProductDTO.UpdateSpec,
) {
return requestClient.put<ProductVO.SpecInfo>(
`/ec/product-spec/update/${id}`,
data,
);
}
/**
* 删除商品规格
*/
export async function deleteProductSpecApi(id: number) {
return requestClient.delete<void>(`/ec/product-spec/delete/${id}`);
return requestClient.delete(`/ec/product-spec/delete/${id}`);
}
/**
@@ -82,26 +95,41 @@ export async function deleteProductSpecApi(id: number) {
* 根据名称精准查询商品
*/
export async function getProductByNameApi(name: string) {
return requestClient.get<ProductVO.Info>(`/ec/product/find-by-name/${encodeURIComponent(name)}`);
return requestClient.get<ProductVO.Info>(
`/ec/product/find-by-name/${encodeURIComponent(name)}`,
);
}
/**
* 批量根据名称查询商品
*/
export async function getProductsByNamesApi(names: string[]) {
return requestClient.post<ProductVO.Info[]>('/ec/product/find-by-names', names);
return requestClient.post<ProductVO.Info[]>(
'/ec/product/find-by-names',
names,
);
}
/**
* 根据商品名称和规格编码精准查询商品规格
*/
export async function getProductSpecByProductAndSpecApi(productName: string, specCode: string) {
return requestClient.get<ProductVO.SpecInfo>(`/ec/product-spec/find-by-product-and-spec/${encodeURIComponent(productName)}/${encodeURIComponent(specCode)}`);
export async function getProductSpecByProductAndSpecApi(
productName: string,
specCode: string,
) {
return requestClient.get<ProductVO.SpecInfo>(
`/ec/product-spec/find-by-product-and-spec/${encodeURIComponent(productName)}/${encodeURIComponent(specCode)}`,
);
}
/**
* 批量根据商品名称和规格编码查询商品规格
*/
export async function getProductSpecsByProductAndSpecsApi(queries: { productName: string; specCode: string }[]) {
return requestClient.post<ProductVO.Info[]>('/ec/product-spec/find-by-product-and-specs', queries);
export async function getProductSpecsByProductAndSpecsApi(
queries: { productName: string; specCode: string }[],
) {
return requestClient.post<ProductVO.Info[]>(
'/ec/product-spec/find-by-product-and-specs',
queries,
);
}
@@ -9,6 +9,8 @@ export namespace ProductDTO {
name: string;
/** 主图图片ID */
mainImageId?: number;
/** 商品规格列表(可选) */
specs?: Spec[];
}
/** 更新商品参数 */
@@ -25,16 +27,6 @@ export namespace ProductDTO {
costPrice: number;
}
/** 一键创建商品和规格参数 */
export interface CreateWithSpecs {
/** 商品名称 */
name: string;
/** 主图图片ID */
mainImageId?: number;
/** 商品规格列表 */
specs: Spec[];
}
/** 商品规格DTO */
export interface Spec {
/** 规格名称 */
@@ -1,8 +1,9 @@
<script lang="ts" setup>
import type { ProductDTO, ProductVO } from '#/api/shop/product/types';
import { computed, onUnmounted, ref } from 'vue';
import { computed, h, onUnmounted, ref, resolveComponent } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import {
@@ -11,27 +12,46 @@ import {
Input,
InputNumber,
message,
Modal,
Space,
Table,
} from 'ant-design-vue';
import { uploadImageApi } from '#/api/media/image';
import {
createProductApi,
createProductWithSpecsApi,
updateProductApi,
} from '#/api/shop/product';
import { createProductApi, updateProductApi } from '#/api/shop/product';
interface Emits {
(e: 'success'): void;
}
defineOptions({ name: 'ProductFormModal' });
const emit = defineEmits<Emits>();
// 创建相机图标组件
// 创建Vben Modal实例
const [Modal, modalApi] = useVbenModal({
title: '添加商品',
class: 'w-[800px]',
draggable: true, // 开启拖拽
contentClass: 'px-6 py-4',
onConfirm: handleSubmit,
onCancel: close,
onOpenChange: (isOpen: boolean) => {
if (isOpen) {
// 打开时不做操作
return;
}
resetForm();
},
});
// 创建图标组件
const CameraIcon = createIconifyIcon('mdi:camera');
const UpIcon = createIconifyIcon('lucide:chevron-up');
const DownIcon = createIconifyIcon('lucide:chevron-down');
const PlusIcon = createIconifyIcon('lucide:plus');
const TrashIcon = createIconifyIcon('lucide:trash-2');
// 内部状态管理
const visible = ref(false);
const isEdit = ref(false);
const currentProductData = ref<null | Partial<ProductVO.Info> | ProductVO.Info>(
null,
@@ -39,7 +59,6 @@ const currentProductData = ref<null | Partial<ProductVO.Info> | ProductVO.Info>(
// 响应式数据
const formRef = ref();
const loading = ref(false);
const newImageFile = ref<File | null>(null); // 新选择的图片文件
const originalImageUrl = ref(''); // 原始图片 URL
const imageLoadError = ref(false); // 图片加载错误状态
@@ -57,9 +76,6 @@ const formData = ref({
const specs = ref<ProductDTO.Spec[]>([]);
const showSpecs = ref(false);
// 模态框标题
const modalTitle = computed(() => (isEdit.value ? '编辑商品' : '添加商品'));
// 当前显示的图片 URL(优先显示新选择的)
const currentImageUrl = computed(() => {
if (newImageFile.value) {
@@ -72,12 +88,15 @@ const currentImageUrl = computed(() => {
function initFormData() {
if (isEdit.value && currentProductData.value) {
// 编辑模式
// 注意:ProductVO.Info 中可能没有 specCode、skuCode、costPrice 字段
// 这些字段可能需要在编辑时从其他地方获取或设置为空
const productData = currentProductData.value as any;
formData.value = {
name: currentProductData.value.name || '',
specCode: '',
skuCode: '',
specCode: productData.specCode || '',
skuCode: productData.skuCode || '',
mainImageId: undefined,
costPrice: 0,
costPrice: productData.costPrice ?? 0,
};
// 设置原始图片 URL
@@ -132,7 +151,7 @@ function resetForm() {
async function handleSubmit() {
try {
await formRef.value?.validate();
loading.value = true;
modalApi.setState({ confirmLoading: true });
// 准备提交数据
const submitData = { ...formData.value };
@@ -161,34 +180,34 @@ async function handleSubmit() {
);
message.success('更新成功');
} else {
// 创建模式:如果有规格,使用一键创建接口
// 创建模式:统一使用创建接口,规格信息作为可选字段
const createData: ProductDTO.Create = {
name: submitData.name,
mainImageId: submitData.mainImageId,
...(specs.value.length > 0 && { specs: specs.value }),
};
await createProductApi(createData);
if (specs.value.length > 0) {
const createWithSpecsData: ProductDTO.CreateWithSpecs = {
name: submitData.name,
mainImageId: submitData.mainImageId,
specs: specs.value,
};
await createProductWithSpecsApi(createWithSpecsData);
message.success('商品和规格创建成功');
} else {
await createProductApi(submitData as ProductDTO.Create);
message.success('创建成功');
}
}
visible.value = false;
close();
emit('success');
} catch (error) {
console.error('保存商品失败:', error);
message.error('保存商品失败');
} finally {
loading.value = false;
modalApi.setState({ confirmLoading: false });
}
}
// 处理取消
function handleCancel() {
visible.value = false;
// 关闭模态框
function close() {
modalApi.close();
resetForm();
}
// 暴露给父组件的方法
@@ -199,10 +218,15 @@ function open(
isEdit.value = editMode;
currentProductData.value = productData || null;
// 更新模态框标题
modalApi.setState({
title: isEdit.value ? '编辑商品' : '添加商品',
});
resetForm(); // 先重置表单
initFormData(); // 再初始化数据
visible.value = true;
modalApi.open();
}
// 暴露方法给父组件
@@ -269,6 +293,80 @@ function removeSpec(index: number) {
specs.value.splice(index, 1);
}
// 表格列配置
const specColumns = [
{
title: '规格名称',
dataIndex: 'name',
key: 'name',
width: '30%',
customRender: ({ record }: { record: ProductDTO.Spec }) => {
return h(Input, {
value: record.name,
placeholder: '请输入规格名称',
'onUpdate:value': (value: string) => {
record.name = value;
},
});
},
},
{
title: '规格编码',
dataIndex: 'specCode',
key: 'specCode',
width: '30%',
customRender: ({ record }: { record: ProductDTO.Spec }) => {
return h(Input, {
value: record.specCode,
placeholder: '请输入规格编码',
'onUpdate:value': (value: string) => {
record.specCode = value;
},
});
},
},
{
title: '成本价',
dataIndex: 'costPrice',
key: 'costPrice',
width: '25%',
customRender: ({ record }: { record: ProductDTO.Spec }) => {
const InputNumberComponent = resolveComponent('InputNumber');
return h(InputNumberComponent, {
value: record.costPrice,
placeholder: '请输入成本价',
min: 0,
precision: 2,
style: { width: '100%' },
'onUpdate:value': (value: null | number) => {
record.costPrice = value ?? 0;
},
});
},
},
{
title: '操作',
key: 'action',
width: '15%',
align: 'center' as const,
customRender: ({ index }: { index: number }) => {
return h(
Button,
{
type: 'text',
danger: true,
size: 'small',
onClick: () => removeSpec(index),
},
{
default: () => '删除',
icon: () => h(TrashIcon, { class: 'h-4 w-4' }),
},
);
},
},
];
// 上传图片并获取图片ID
async function uploadImageAndGetId(): Promise<number | undefined> {
if (!newImageFile.value) {
@@ -302,14 +400,7 @@ onUnmounted(() => {
</script>
<template>
<Modal
:open="visible"
:title="modalTitle"
width="600px"
:confirm-loading="loading"
@ok="handleSubmit"
@cancel="handleCancel"
>
<Modal>
<Form
ref="formRef"
:model="formData"
@@ -441,61 +532,50 @@ onUnmounted(() => {
style="width: 100%"
:min="0"
:precision="2"
:step="0.01"
/>
</Form.Item>
<!-- 规格管理 -->
<Form.Item v-if="!isEdit" label="商品规格">
<div class="space-y-4">
<div class="flex items-center gap-2">
<Button
type="dashed"
@click="showSpecs = !showSpecs"
:icon="showSpecs ? 'up' : 'down'"
>
{{ showSpecs ? '收起规格' : '添加规格' }}
<div class="flex items-center justify-between">
<Space>
<Button type="dashed" @click="showSpecs = !showSpecs">
<template #icon>
<component
:is="showSpecs ? UpIcon : DownIcon"
class="h-4 w-4"
/>
</template>
{{ showSpecs ? '收起规格' : '添加规格' }}
</Button>
</Space>
<Button v-if="showSpecs" type="primary" @click="addSpec">
<template #icon>
<PlusIcon class="h-4 w-4" />
</template>
添加规格
</Button>
<span class="text-sm text-gray-500">
可以添加多个规格,每个规格包含名称、编码和成本价
</span>
</div>
<div
v-if="showSpecs"
class="rounded-lg border border-gray-200 bg-gray-50 p-4"
class="rounded-lg border border-gray-200 bg-white p-4"
>
<div class="space-y-3">
<div
v-for="(spec, index) in specs"
:key="index"
class="flex items-center gap-2 rounded border bg-white p-3"
>
<Input
v-model:value="spec.name"
placeholder="规格名称"
style="flex: 1"
/>
<Input
v-model:value="spec.specCode"
placeholder="规格编码"
style="flex: 1"
/>
<InputNumber
v-model:value="spec.costPrice"
placeholder="成本价"
style="width: 120px"
:min="0"
:precision="2"
/>
<Button type="text" danger @click="removeSpec(index)">
删除
</Button>
</div>
<Button type="dashed" @click="addSpec" style="width: 100%">
+ 添加规格
</Button>
</div>
<Table
:columns="specColumns"
:data-source="specs"
:pagination="false"
row-key="index"
size="small"
>
<template #emptyText>
<div class="py-4 text-center text-gray-400">
暂无规格,点击上方"添加规格"按钮添加
</div>
</template>
</Table>
</div>
</div>
</Form.Item>
@@ -2,7 +2,9 @@
import type { ProductDTO, ProductVO } from '#/api/shop/product/types';
import type { PageQueryDTO } from '#/types/common';
import { computed, h, ref } from 'vue';
import { h, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import {
Button,
@@ -10,7 +12,6 @@ import {
Input,
InputNumber,
message,
Modal,
Table,
} from 'ant-design-vue';
@@ -28,11 +29,9 @@ interface Emits {
const emit = defineEmits<Emits>();
// 内部状态管理
const visible = ref(false);
const currentProduct = ref<null | ProductVO.Info>(null);
// 响应式数据
const loading = ref(false);
const specLoading = ref(false);
const specList = ref<ProductVO.SpecInfo[]>([]);
const specTotal = ref(0);
@@ -40,8 +39,6 @@ const specCurrent = ref(1);
const specPageSize = ref(10);
// 规格表单相关
const specFormVisible = ref(false);
const specFormLoading = ref(false);
const specFormRef = ref();
const isEditSpec = ref(false);
const currentSpecId = ref<null | number>(null);
@@ -52,15 +49,85 @@ const specFormData = ref({
costPrice: 0,
});
// 模态框标题
const modalTitle = computed(() =>
currentProduct.value ? `管理规格 - ${currentProduct.value.name}` : '管理规格',
);
// 声明模态框 API(稍后赋值)
let modalApi: ReturnType<typeof useVbenModal>[1];
let specFormModalApi: ReturnType<typeof useVbenModal>[1];
// 规格表单标题
const specFormTitle = computed(() =>
isEditSpec.value ? '编辑规格' : '添加规格',
);
// 处理取消
function handleCancel() {
modalApi?.close();
}
// 处理规格表单取消
function handleSpecCancel() {
specFormModalApi?.close();
}
// 处理规格表单提交
async function handleSpecSubmit() {
try {
await specFormRef.value?.validate();
specFormModalApi?.setState({ confirmLoading: true });
if (isEditSpec.value && currentSpecId.value) {
await updateProductSpecApi(
currentSpecId.value,
specFormData.value as ProductDTO.UpdateSpec,
);
message.success('更新成功');
} else {
if (!currentProduct.value) {
message.error('商品信息不存在');
return;
}
const createData: ProductDTO.CreateSpec = {
productId: currentProduct.value.id,
...specFormData.value,
};
await createProductSpecApi(createData);
message.success('创建成功');
}
specFormModalApi?.close();
await fetchSpecList();
} catch (error) {
console.error('保存规格失败:', error);
message.error('保存规格失败');
} finally {
specFormModalApi?.setState({ confirmLoading: false });
}
}
// 创建主模态框
const [Modal, _modalApi] = useVbenModal({
title: '管理规格',
draggable: true,
class: 'w-[800px]',
contentClass: 'px-6 py-4',
showConfirmButton: false,
showCancelButton: false,
onCancel: handleCancel,
onOpenChange: (isOpen: boolean) => {
if (!isOpen) {
emit('success');
}
},
});
modalApi = _modalApi;
// 创建规格表单模态框
const [SpecFormModal, _specFormModalApi] = useVbenModal({
title: '添加规格',
draggable: true,
contentClass: 'px-6 py-4',
onConfirm: handleSpecSubmit,
onCancel: handleSpecCancel,
});
specFormModalApi = _specFormModalApi;
// 模态框标题(通过 modalApi 动态更新)
// 规格表单标题(通过 specFormModalApi 动态更新)
// 表格列配置
const columns = [
@@ -160,7 +227,8 @@ function handleAddSpec() {
specCode: '',
costPrice: 0,
};
specFormVisible.value = true;
specFormModalApi.setState({ title: '添加规格' });
specFormModalApi.open();
}
// 处理编辑规格
@@ -172,7 +240,8 @@ function handleEditSpec(record: ProductVO.SpecInfo) {
specCode: record.specCode || '',
costPrice: record.costPrice,
};
specFormVisible.value = true;
specFormModalApi.setState({ title: '编辑规格' });
specFormModalApi.open();
}
// 处理删除规格
@@ -187,65 +256,15 @@ async function handleDeleteSpec(record: ProductVO.SpecInfo) {
}
}
// 处理规格表单提交
async function handleSpecSubmit() {
try {
await specFormRef.value?.validate();
specFormLoading.value = true;
if (isEditSpec.value && currentSpecId.value) {
await updateProductSpecApi(
currentSpecId.value,
specFormData.value as ProductDTO.UpdateSpec,
);
message.success('更新成功');
} else {
if (!currentProduct.value) {
message.error('商品信息不存在');
return;
}
const createData: ProductDTO.CreateSpec = {
productId: currentProduct.value.id,
...specFormData.value,
};
await createProductSpecApi(createData);
message.success('创建成功');
}
specFormVisible.value = false;
await fetchSpecList();
} catch (error) {
console.error('保存规格失败:', error);
message.error('保存规格失败');
} finally {
specFormLoading.value = false;
}
}
// 处理规格表单取消
function handleSpecCancel() {
specFormVisible.value = false;
}
// 处理提交
function handleSubmit() {
// 规格管理模态框不需要提交操作
handleCancel();
}
// 处理取消
function handleCancel() {
visible.value = false;
emit('success');
}
// 暴露给父组件的方法
function open(product: ProductVO.Info) {
currentProduct.value = product;
specCurrent.value = 1;
specPageSize.value = 10;
visible.value = true;
modalApi.setState({
title: `管理规格 - ${product.name}`,
});
modalApi.open();
fetchSpecList();
}
@@ -256,14 +275,7 @@ defineExpose({
</script>
<template>
<Modal
:open="visible"
:title="modalTitle"
width="800px"
:confirm-loading="loading"
@ok="handleSubmit"
@cancel="handleCancel"
>
<Modal>
<div class="space-y-4">
<!-- 商品信息 -->
<div class="rounded-lg bg-gray-50 p-4">
@@ -308,14 +320,7 @@ defineExpose({
</Modal>
<!-- 规格表单模态框 -->
<Modal
:open="specFormVisible"
:title="specFormTitle"
width="500px"
:confirm-loading="specFormLoading"
@ok="handleSpecSubmit"
@cancel="handleSpecCancel"
>
<SpecFormModal>
<Form
ref="specFormRef"
:model="specFormData"
@@ -351,5 +356,5 @@ defineExpose({
/>
</Form.Item>
</Form>
</Modal>
</SpecFormModal>
</template>