refactor: improve code formatting and structure in product index view

- Enhanced readability by adjusting indentation and spacing in the template.
- Consolidated repeated code blocks for better maintainability.
- Added functionality for changing product status (上架/下架) with confirmation prompts.
- Updated the handleDelete function to maintain consistent formatting.
- Ensured all API calls and data handling are properly formatted for clarity.
This commit is contained in:
2026-03-08 02:38:43 +07:00
parent a8fab3e765
commit 0e0b856edb
3 changed files with 1036 additions and 916 deletions

View File

@@ -42,3 +42,16 @@ export function delProduct(id) {
method: 'delete'
})
}
// 上架/下架商品
export function changeProductStatus(id, status) {
const data = {
id,
status
}
return request({
url: '/service/product/status',
method: 'put',
data: data
})
}

View File

@@ -1,8 +1,15 @@
<template>
<div class="app-container">
<!-- 商品基本信息 -->
<div class="background-color-fff padding-20 border-radius-8px margin-bottom-20">
<el-form ref="productRef" :model="form" :rules="rules" label-width="100px">
<div
class="background-color-fff padding-20 border-radius-8px margin-bottom-20"
>
<el-form
ref="productRef"
:model="form"
:rules="rules"
label-width="100px"
>
<el-form-item label="商品分类" prop="categoryId">
<el-select
v-model="form.categoryId"
@@ -33,7 +40,9 @@
<!-- SKU管理 -->
<div class="sku-management">
<div class="sku-header flex justify-between items-center margin-bottom-20">
<div
class="sku-header flex justify-between items-center margin-bottom-20"
>
<h3 class="text-16 font-600">商品规格(SKU)</h3>
<el-button type="primary" @click="handleAddSku" size="small">
<i class="el-icon-plus"></i>
@@ -46,8 +55,18 @@
v-if="form.productSkuList && form.productSkuList.length > 0"
class="sku-table-wrapper"
>
<el-table :data="form.productSkuList" border size="small" class="sku-table">
<el-table-column type="index" width="50" label="序号" align="center" />
<el-table
:data="form.productSkuList"
border
size="small"
class="sku-table"
>
<el-table-column
type="index"
width="50"
label="序号"
align="center"
/>
<el-table-column prop="skuCode" label="SKU编码" min-width="120">
<template #default="{ row, $index }">
<el-input
@@ -76,7 +95,12 @@
</div>
</template>
</el-table-column>
<el-table-column prop="price" label="销售价" width="180" align="left">
<el-table-column
prop="price"
label="销售价"
width="180"
align="left"
>
<template #default="{ row }">
<el-input
v-model.number="row.price"
@@ -154,11 +178,16 @@
:label="$index"
@change="setDefaultSku($index)"
>
{{ row.isDefault === 1 ? '是' : '否' }}
{{ row.isDefault === 1 ? "是" : "否" }}
</el-radio>
</template>
</el-table-column>
<el-table-column prop="isEnable" label="状态" width="80" align="center">
<el-table-column
prop="isEnable"
label="状态"
width="80"
align="center"
>
<template #default="{ row }">
<el-switch
v-model="row.isEnable"
@@ -168,7 +197,12 @@
/>
</template>
</el-table-column>
<el-table-column label="操作" width="100" align="center" fixed="right">
<el-table-column
label="操作"
width="100"
align="center"
fixed="right"
>
<template #default="{ row, $index }">
<el-button
type="text"
@@ -195,10 +229,10 @@
}}
</el-tag>
<el-tag :type="hasDuplicateSku ? 'danger' : 'success'">
{{ hasDuplicateSku ? '有重复SKU编码' : 'SKU编码无重复' }}
{{ hasDuplicateSku ? "有重复SKU编码" : "SKU编码无重复" }}
</el-tag>
<el-tag :type="hasSkuValidationError ? 'danger' : 'success'">
{{ hasSkuValidationError ? '存在验证错误' : 'SKU信息完整' }}
{{ hasSkuValidationError ? "存在验证错误" : "SKU信息完整" }}
</el-tag>
</el-space>
</div>
@@ -206,7 +240,10 @@
<!-- 无SKU提示 -->
<div v-else class="empty-sku">
<el-empty description="暂无SKU请点击上方按钮添加" :image-size="60" />
<el-empty
description="暂无SKU请点击上方按钮添加"
:image-size="60"
/>
</div>
</div>
@@ -281,9 +318,9 @@
</template>
<script setup name="ProductDetailWithSku">
import { useRoute, useRouter } from 'vue-router';
import { getProduct, addProduct, updateProduct } from '@/api/service/product';
import { listProductCategory } from '@/api/service/productCategory';
import { useRoute, useRouter } from "vue-router";
import { getProduct, addProduct, updateProduct } from "@/api/service/product";
import { listProductCategory } from "@/api/service/productCategory";
const { proxy } = getCurrentInstance();
const route = useRoute();
@@ -319,24 +356,30 @@ const data = reactive({
defaultSkuIndex: -1, // 默认SKU索引
},
rules: {
categoryId: [{ required: true, message: '商品分类不能为空', trigger: 'blur' }],
productName: [{ required: true, message: '商品名称不能为空', trigger: 'blur' }],
mainImage: [{ required: true, message: '主图URL不能为空', trigger: 'blur' }],
unit: [{ required: true, message: '商品单位不能为空', trigger: 'blur' }],
categoryId: [
{ required: true, message: "商品分类不能为空", trigger: "blur" },
],
productName: [
{ required: true, message: "商品名称不能为空", trigger: "blur" },
],
mainImage: [
{ required: true, message: "主图URL不能为空", trigger: "blur" },
],
unit: [{ required: true, message: "商品单位不能为空", trigger: "blur" }],
productSkuList: [
{
validator: (rule, value, callback) => {
if (!value || value.length === 0) {
callback(new Error('请至少添加一个SKU'));
callback(new Error("请至少添加一个SKU"));
} else if (data.hasDuplicateSku) {
callback(new Error('存在重复的SKU编码请检查'));
callback(new Error("存在重复的SKU编码请检查"));
} else if (data.hasSkuValidationError) {
callback(new Error('SKU信息填写不完整或有误请检查'));
callback(new Error("SKU信息填写不完整或有误请检查"));
} else {
callback();
}
},
trigger: 'blur',
trigger: "blur",
},
],
},
@@ -354,19 +397,21 @@ const totalStock = computed(() => {
const hasDuplicateSku = computed(() => {
if (!form.value.productSkuList) return false;
const skuCodes = form.value.productSkuList.map(sku => sku.skuCode?.trim()).filter(code => code);
const skuCodes = form.value.productSkuList
.map((sku) => sku.skuCode?.trim())
.filter((code) => code);
return new Set(skuCodes).size !== skuCodes.length;
});
const hasSkuValidationError = computed(() => {
if (!form.value.productSkuList) return false;
return form.value.productSkuList.some(
sku =>
(sku) =>
sku.skuError ||
sku.specTextError ||
sku.priceError ||
sku.originalPriceError ||
sku.stockQuantityError
sku.stockQuantityError,
);
});
@@ -375,24 +420,24 @@ const initSkuData = () => {
return {
id: null,
productId: null,
skuCode: '',
specData: '',
specText: '',
skuCode: "",
specData: "",
specText: "",
price: 0,
originalPrice: 0,
stockQuantity: 0,
warningStock: 0,
salesVolume: 0,
skuImage: '',
barcode: '',
skuImage: "",
barcode: "",
isDefault: 0,
isEnable: 1,
// 错误信息字段
skuError: '',
specTextError: '',
priceError: '',
originalPriceError: '',
stockQuantityError: '',
skuError: "",
specTextError: "",
priceError: "",
originalPriceError: "",
stockQuantityError: "",
};
};
@@ -416,15 +461,15 @@ const handleAddSku = () => {
// 生成SKU编码
const generateSkuCode = () => {
const spuCode = form.value.spuCode || 'SPU';
const spuCode = form.value.spuCode || "SPU";
const timestamp = new Date().getTime().toString().slice(-6);
const random = Math.random().toString(36).substr(2, 4).toUpperCase();
return `${spuCode}_${timestamp}${random}`;
};
// 删除SKU
const handleRemoveSku = index => {
proxy.$modal.confirm('确定要删除这个SKU吗').then(() => {
const handleRemoveSku = (index) => {
proxy.$modal.confirm("确定要删除这个SKU吗").then(() => {
form.value.productSkuList.splice(index, 1);
// 如果删除的是默认SKU重置默认索引
@@ -442,7 +487,7 @@ const handleRemoveSku = index => {
};
// 设置默认SKU
const setDefaultSku = index => {
const setDefaultSku = (index) => {
form.value.defaultSkuIndex = index;
form.value.productSkuList.forEach((sku, i) => {
sku.isDefault = i === index ? 1 : 0;
@@ -452,7 +497,7 @@ const setDefaultSku = index => {
// 验证SKU编码
const validateSkuCode = (row, index) => {
// 清除之前的错误
row.skuError = '';
row.skuError = "";
// if (!row.skuCode || row.skuCode.trim() === '') {
// row.skuError = 'SKU编码不能为空';
@@ -461,11 +506,11 @@ const validateSkuCode = (row, index) => {
// 检查重复
const duplicateIndex = form.value.productSkuList.findIndex(
(sku, i) => i !== index && sku.skuCode === row.skuCode
(sku, i) => i !== index && sku.skuCode === row.skuCode,
);
if (duplicateIndex !== -1) {
row.skuError = 'SKU编码已存在';
row.skuError = "SKU编码已存在";
return false;
}
@@ -473,12 +518,12 @@ const validateSkuCode = (row, index) => {
};
// 验证规格文本
const validateSpecText = row => {
const validateSpecText = (row) => {
// 清除之前的错误
row.specTextError = '';
row.specTextError = "";
if (!row.specText || row.specText.trim() === '') {
row.specTextError = '规格文本不能为空';
if (!row.specText || row.specText.trim() === "") {
row.specTextError = "规格文本不能为空";
return false;
}
@@ -486,28 +531,28 @@ const validateSpecText = row => {
};
// 验证销售价格
const validatePrice = row => {
const validatePrice = (row) => {
// 清除之前的错误
row.priceError = '';
row.priceError = "";
if (row.price === null || row.price === undefined || row.price === '') {
row.priceError = '销售价不能为空';
if (row.price === null || row.price === undefined || row.price === "") {
row.priceError = "销售价不能为空";
return false;
}
const price = Number(row.price);
if (isNaN(price)) {
row.priceError = '请输入有效的数字';
row.priceError = "请输入有效的数字";
return false;
}
if (price < 0) {
row.priceError = '价格不能为负数';
row.priceError = "价格不能为负数";
return false;
}
if (price === 0) {
row.priceError = '价格不能为0';
row.priceError = "价格不能为0";
return false;
}
@@ -515,23 +560,27 @@ const validatePrice = row => {
};
// 验证原价
const validateOriginalPrice = row => {
const validateOriginalPrice = (row) => {
// 清除之前的错误
row.originalPriceError = '';
row.originalPriceError = "";
if (row.originalPrice === null || row.originalPrice === undefined || row.originalPrice === '') {
row.originalPriceError = '原价不能为空';
if (
row.originalPrice === null ||
row.originalPrice === undefined ||
row.originalPrice === ""
) {
row.originalPriceError = "原价不能为空";
return false;
}
const originalPrice = Number(row.originalPrice);
if (isNaN(originalPrice)) {
row.originalPriceError = '请输入有效的数字';
row.originalPriceError = "请输入有效的数字";
return false;
}
if (originalPrice < 0) {
row.originalPriceError = '原价不能为负数';
row.originalPriceError = "原价不能为负数";
return false;
}
@@ -539,29 +588,33 @@ const validateOriginalPrice = row => {
};
// 验证库存
const validateStockQuantity = row => {
const validateStockQuantity = (row) => {
// 清除之前的错误
row.stockQuantityError = '';
row.stockQuantityError = "";
if (row.stockQuantity === null || row.stockQuantity === undefined || row.stockQuantity === '') {
row.stockQuantityError = '库存不能为空';
if (
row.stockQuantity === null ||
row.stockQuantity === undefined ||
row.stockQuantity === ""
) {
row.stockQuantityError = "库存不能为空";
return false;
}
const stockQuantity = Number(row.stockQuantity);
if (isNaN(stockQuantity)) {
row.stockQuantityError = '请输入有效的数字';
row.stockQuantityError = "请输入有效的数字";
return false;
}
if (stockQuantity < 0) {
row.stockQuantityError = '库存不能为负数';
row.stockQuantityError = "库存不能为负数";
return false;
}
// 检查是否为整数
if (!Number.isInteger(stockQuantity)) {
row.stockQuantityError = '库存必须为整数';
row.stockQuantityError = "库存必须为整数";
return false;
}
@@ -596,18 +649,18 @@ const validateAllSkuFields = () => {
};
// 格式化规格数据
const formatSpecData = row => {
const formatSpecData = (row) => {
if (!row.specData) return;
try {
// 如果是JSON字符串尝试解析
if (row.specData.trim().startsWith('{')) {
if (row.specData.trim().startsWith("{")) {
const specObj = JSON.parse(row.specData);
// 生成规格文本
row.specText = Object.values(specObj).join('/');
row.specText = Object.values(specObj).join("/");
}
} catch (e) {
console.warn('规格数据格式错误:', e);
console.warn("规格数据格式错误:", e);
}
};
@@ -620,9 +673,9 @@ const updatePriceRange = () => {
}
const prices = form.value.productSkuList
.filter(sku => sku.isEnable === 1)
.map(sku => Number(sku.price) || 0)
.filter(price => price > 0);
.filter((sku) => sku.isEnable === 1)
.map((sku) => Number(sku.price) || 0)
.filter((price) => price > 0);
if (prices.length === 0) {
form.value.minPrice = 0;
@@ -640,7 +693,7 @@ watch(
() => {
updatePriceRange();
},
{ deep: true }
{ deep: true },
);
// 获取商品详情
@@ -654,17 +707,17 @@ const getProductDetail = async () => {
if (productData.productSkuList && productData.productSkuList.length > 0) {
// 找到默认SKU的索引
const defaultIndex = productData.productSkuList.findIndex(
sku => sku.isDefault === 1
(sku) => sku.isDefault === 1,
);
productData.defaultSkuIndex = defaultIndex;
// 初始化错误字段
productData.productSkuList.forEach(sku => {
sku.skuError = '';
sku.specTextError = '';
sku.priceError = '';
sku.originalPriceError = '';
sku.stockQuantityError = '';
productData.productSkuList.forEach((sku) => {
sku.skuError = "";
sku.specTextError = "";
sku.priceError = "";
sku.originalPriceError = "";
sku.stockQuantityError = "";
});
} else {
productData.productSkuList = [];
@@ -673,8 +726,8 @@ const getProductDetail = async () => {
form.value = productData;
} catch (error) {
console.error('获取商品详情失败:', error);
proxy.$modal.msgError('获取商品信息失败');
console.error("获取商品详情失败:", error);
proxy.$modal.msgError("获取商品信息失败");
}
} else {
// 新增商品时初始化一个默认SKU
@@ -691,7 +744,7 @@ const prepareSubmitData = () => {
// 确保SKU列表中的productId正确
if (submitData.productSkuList) {
submitData.productSkuList.forEach(sku => {
submitData.productSkuList.forEach((sku) => {
if (!sku.id) {
delete sku.id; // 新增的SKU不应该有id
}
@@ -715,12 +768,12 @@ const submitForm = async () => {
// 先验证所有SKU字段
const isSkuValid = validateAllSkuFields();
if (!isSkuValid) {
proxy.$modal.msgWarning('请检查SKU信息填写是否完整');
proxy.$modal.msgWarning("请检查SKU信息填写是否完整");
return;
}
if (hasDuplicateSku.value) {
proxy.$modal.msgWarning('存在重复的SKU编码请检查');
proxy.$modal.msgWarning("存在重复的SKU编码请检查");
return;
}
@@ -728,7 +781,7 @@ const submitForm = async () => {
await proxy.$refs.productRef.validate();
if (!form.value.productSkuList || form.value.productSkuList.length === 0) {
proxy.$modal.msgWarning('请至少添加一个SKU');
proxy.$modal.msgWarning("请至少添加一个SKU");
return;
}
@@ -739,10 +792,10 @@ const submitForm = async () => {
let response;
if (submitData.id) {
response = await updateProduct(submitData);
proxy.$modal.msgSuccess('修改成功');
proxy.$modal.msgSuccess("修改成功");
} else {
response = await addProduct(submitData);
proxy.$modal.msgSuccess('新增成功');
proxy.$modal.msgSuccess("新增成功");
}
// 处理响应
@@ -753,8 +806,8 @@ const submitForm = async () => {
}, 1500);
}
} catch (error) {
console.error('保存失败:', error);
proxy.$modal.msgError(error.message || '保存失败');
console.error("保存失败:", error);
proxy.$modal.msgError(error.message || "保存失败");
} finally {
submitLoading.value = false;
}
@@ -762,12 +815,12 @@ const submitForm = async () => {
// 取消
const cancel = () => {
proxy.$modal.confirm('确定要取消吗?未保存的数据将会丢失。').then(() => {
proxy.$modal.confirm("确定要取消吗?未保存的数据将会丢失。").then(() => {
proxy.$tab.closePage();
});
};
const remoteMethod = query => {
const remoteMethod = (query) => {
if (query) {
getProductList(query.toLowerCase());
} else {
@@ -776,11 +829,11 @@ const remoteMethod = query => {
/** 查询商品分类列表 */
function getList(name) {
listProductCategory(proxy.CloneData({ pageNum: 1, pageSize: 100, productName: name })).then(
response => {
listProductCategory(
proxy.CloneData({ pageNum: 1, pageSize: 100, productName: name }),
).then((response) => {
productCategoryList.value = response.rows;
}
);
});
}
// 初始化加载

View File

@@ -1,6 +1,8 @@
<template>
<div class="app-container">
<div class="background-color-fff padding-20 border-radius-8px margin-bottom-20">
<div
class="background-color-fff padding-20 border-radius-8px margin-bottom-20"
>
<el-form
:model="queryParams"
ref="queryRef"
@@ -25,13 +27,17 @@
/>
</el-form-item>
<el-form-item>
<el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
<el-button type="primary" icon="Search" @click="handleQuery"
>搜索</el-button
>
<el-button icon="Refresh" @click="resetQuery">重置</el-button>
</el-form-item>
</el-form>
</div>
<div class="background-color-fff padding-20 border-radius-8px margin-bottom-20">
<div
class="background-color-fff padding-20 border-radius-8px margin-bottom-20"
>
<el-row :gutter="10" class="mb8">
<el-col :span="1.5">
<el-button
@@ -86,7 +92,9 @@
</el-row>
</div>
<div class="background-color-fff padding-20 border-radius-8px margin-bottom-20">
<div
class="background-color-fff padding-20 border-radius-8px margin-bottom-20"
>
<el-table
v-loading="loading"
:data="productList"
@@ -98,9 +106,18 @@
<el-table-column label="商品编码" align="center" prop="spuCode" />
<el-table-column label="商品名称" align="center" prop="productName" />
<el-table-column label="副标题" align="center" prop="subTitle" />
<el-table-column label="主图URL" align="center" prop="mainImage" width="100">
<el-table-column
label="主图URL"
align="center"
prop="mainImage"
width="100"
>
<template #default="scope">
<image-preview :src="scope.row.mainImage" :width="50" :height="50" />
<image-preview
:src="scope.row.mainImage"
:width="50"
:height="50"
/>
</template>
</el-table-column>
<!-- <el-table-column label="商品相册" align="center" prop="imageGallery" width="100">
@@ -136,6 +153,26 @@
>
修改
</el-button>
<el-button
link
type="primary"
icon="Edit"
v-if="scope.row.status === 0"
@click="handleChangeStatus(scope.row, 1)"
v-hasPermi="['service:product:edit']"
>
上架
</el-button>
<el-button
link
type="primary"
icon="Edit"
v-if="scope.row.status === 1"
@click="handleChangeStatus(scope.row, 0)"
v-hasPermi="['service:product:edit']"
>
下架
</el-button>
<el-button
link
type="primary"
@@ -167,7 +204,8 @@ import {
delProduct,
addProduct,
updateProduct,
} from '@/api/service/product';
changeProductStatus,
} from "@/api/service/product";
const { proxy } = getCurrentInstance();
const router = useRouter();
@@ -180,7 +218,7 @@ const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref('');
const title = ref("");
const data = reactive({
form: {},
@@ -213,7 +251,7 @@ const { queryParams, form } = toRefs(data);
/** 查询商品列表列表 */
function getList() {
loading.value = true;
listProduct(queryParams.value).then(response => {
listProduct(queryParams.value).then((response) => {
productList.value = response.rows;
total.value = response.total;
loading.value = false;
@@ -253,7 +291,7 @@ function reset() {
updateBy: null,
updateTime: null,
};
proxy.resetForm('productRef');
proxy.resetForm("productRef");
}
/** 搜索按钮操作 */
@@ -264,13 +302,13 @@ function handleQuery() {
/** 重置按钮操作 */
function resetQuery() {
proxy.resetForm('queryRef');
proxy.resetForm("queryRef");
handleQuery();
}
// 多选框选中数据
function handleSelectionChange(selection) {
ids.value = selection.map(item => item.id);
ids.value = selection.map((item) => item.id);
single.value = selection.length != 1;
multiple.value = !selection.length;
}
@@ -278,8 +316,8 @@ function handleSelectionChange(selection) {
/** 新增按钮操作 */
function handleAdd() {
router.push({
path: 'productDetails',
name: 'ProductDetails',
path: "productDetails",
name: "ProductDetails",
});
}
@@ -288,8 +326,8 @@ function handleUpdate(row) {
reset();
const _id = row.id || ids.value;
router.push({
path: 'productDetails',
name: 'ProductDetails',
path: "productDetails",
name: "ProductDetails",
query: {
productId: _id,
},
@@ -298,17 +336,17 @@ function handleUpdate(row) {
/** 提交按钮 */
function submitForm() {
proxy.$refs['productRef'].validate(valid => {
proxy.$refs["productRef"].validate((valid) => {
if (valid) {
if (form.value.id != null) {
updateProduct(form.value).then(response => {
proxy.$modal.msgSuccess('修改成功');
updateProduct(form.value).then((response) => {
proxy.$modal.msgSuccess("修改成功");
open.value = false;
getList();
});
} else {
addProduct(form.value).then(response => {
proxy.$modal.msgSuccess('新增成功');
addProduct(form.value).then((response) => {
proxy.$modal.msgSuccess("新增成功");
open.value = false;
getList();
});
@@ -317,6 +355,22 @@ function submitForm() {
});
}
/** 上架/下架按钮操作 */
function handleChangeStatus(row, status) {
const _ids = row.id || ids.value;
const action = status === 1 ? "上架" : "下架";
proxy.$modal
.confirm(`是否确认${action}商品列表编号为"${_ids}"的数据项?`)
.then(function () {
return changeProductStatus(_ids, status);
})
.then(() => {
getList();
proxy.$modal.msgSuccess(`${action}成功`);
})
.catch(() => {});
}
/** 删除按钮操作 */
function handleDelete(row) {
const _ids = row.id || ids.value;
@@ -327,7 +381,7 @@ function handleDelete(row) {
})
.then(() => {
getList();
proxy.$modal.msgSuccess('删除成功');
proxy.$modal.msgSuccess("删除成功");
})
.catch(() => {});
}
@@ -335,11 +389,11 @@ function handleDelete(row) {
/** 导出按钮操作 */
function handleExport() {
proxy.download(
'service/product/export',
"service/product/export",
{
...queryParams.value,
},
`product_${new Date().getTime()}.xlsx`
`product_${new Date().getTime()}.xlsx`,
);
}