This commit is contained in:
jiangzewen committed 2025-05-12 18:21:12 +08:00
1 parent 9dc409b4f9
commit 5b24a8abb6
18 files changed
+2796 -5

No files matched your search

+3 -3
View File
@@ -1,6 +1,6 @@
import request from '@/config/axios'
import { useUserStore } from '@/store/modules/user';
const UserVO = useUserStore();
export interface Property {
propertyId?: number // 属性编号
propertyName?: string // 属性名称
@@ -59,14 +59,14 @@ export interface Spu {
stock?: number // 商品库存
createTime?: Date // 商品创建时间
status?: number // 商品状态
types?: number // 商品类型
}
// 获得 Spu 列表
export const getSpuPage = (params: PageParam) => {
// /product/spu/page
return request.get({ url: '/product/spu/pageWithCreator',params:{
...params,
creator:UserVO.user.id
...params
}})
}
+40
View File
@@ -345,6 +345,7 @@ const remainingRouter: AppRouteRecordRaw[] = [
}
]
},
{
path: '/mall/product', // 商品中心
component: Layout,
@@ -353,6 +354,45 @@ const remainingRouter: AppRouteRecordRaw[] = [
hidden: true
},
children: [
{
path: 'containergoods/add',
component: () => import('@/views/mall/product/containergoods/form/index.vue'),
name: 'ProductPickupAdd',
meta: {
noCache: false, // 需要缓存
hidden: true,
canTo: true,
icon: 'ep:edit',
title: '商品添加',
activeMenu: '/mall/product/containergoods'
}
},
{
path: 'spu/edit/:id(\\d+)',
component: () => import('@/views/mall/product/containergoods/form/index.vue'),
name: 'ProductPickupEdit',
meta: {
noCache: true,
hidden: true,
canTo: true,
icon: 'ep:edit',
title: '商品编辑',
activeMenu: '/mall/product/containergoods'
}
},
{
path: 'spu/detail/:id(\\d+)',
component: () => import('@/views/mall/product/containergoods/form/index.vue'),
name: 'ProductPickupDetail',
meta: {
noCache: true,
hidden: true,
canTo: true,
icon: 'ep:view',
title: '商品详情',
activeMenu: '/mall/product/containergoods'
}
},
{
path: 'spu/add',
component: () => import('@/views/mall/product/spu/form/index.vue'),
@@ -0,0 +1,576 @@
<template>
<!-- 情况一:添加/修改 -->
<el-table
v-if="!isDetail && !isActivityComponent"
:data="isBatch ? skuList : formData!.skus!"
border
class="tabNumWidth"
max-height="500"
size="small"
>
<el-table-column align="center" label="图片" min-width="65">
<template #default="{ row }">
<UploadImg v-model="row.picUrl" height="50px" width="50px" />
</template>
</el-table-column>
<template v-if="formData!.specType && !isBatch">
<!-- 根据商品属性动态添加 -->
<el-table-column
v-for="(item, index) in tableHeaders"
:key="index"
:label="item.label"
align="center"
min-width="120"
>
<template #default="{ row }">
<span style="font-weight: bold; color: #40aaff">
{{ row.properties?.[index]?.valueName }}
</span>
</template>
</el-table-column>
</template>
<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>
<el-table-column align="center" label="销售价" min-width="168">
<template #default="{ row }">
<el-input-number
v-model="row.price"
:min="0"
:precision="2"
:step="0.1"
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"
:precision="2"
:step="0.1"
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"
:precision="2"
:step="0.1"
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"
:precision="2"
:step="0.1"
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"
:precision="2"
:step="0.1"
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.firstBrokeragePrice"
:min="0"
:precision="2"
:step="0.1"
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.secondBrokeragePrice"
:min="0"
:precision="2"
:step="0.1"
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="{ row }">
<el-button v-if="isBatch" link size="small" type="primary" @click="batchAdd">
批量添加
</el-button>
<el-button v-else link size="small" type="primary" @click="deleteSku(row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<!-- 情况二:详情 -->
<el-table
v-if="isDetail"
ref="activitySkuListRef"
:data="formData!.skus!"
border
max-height="500"
size="small"
style="width: 99%"
@selection-change="handleSelectionChange"
>
<el-table-column v-if="isComponent" type="selection" width="45" />
<el-table-column align="center" label="图片" min-width="80">
<template #default="{ row }">
<el-image
v-if="row.picUrl"
:src="row.picUrl"
class="h-50px w-50px"
@click="imagePreview(row.picUrl)"
/>
</template>
</el-table-column>
<template v-if="formData!.specType && !isBatch">
<!-- 根据商品属性动态添加 -->
<el-table-column
v-for="(item, index) in tableHeaders"
:key="index"
:label="item.label"
align="center"
min-width="80"
>
<template #default="{ row }">
<span style="font-weight: bold; color: #40aaff">
{{ row.properties?.[index]?.valueName }}
</span>
</template>
</el-table-column>
</template>
<el-table-column align="center" label="商品条码" min-width="100">
<template #default="{ row }">
{{ row.barCode }}
</template>
</el-table-column>
<el-table-column align="center" label="销售价(元)" min-width="80">
<template #default="{ row }">
{{ row.price }}
</template>
</el-table-column>
<el-table-column align="center" label="市场价(元)" min-width="80">
<template #default="{ row }">
{{ row.marketPrice }}
</template>
</el-table-column>
<el-table-column align="center" label="成本价(元)" min-width="80">
<template #default="{ row }">
{{ row.costPrice }}
</template>
</el-table-column>
<el-table-column align="center" label="库存" min-width="80">
<template #default="{ row }">
{{ row.stock }}
</template>
</el-table-column>
<el-table-column align="center" label="重量(kg)" min-width="80">
<template #default="{ row }">
{{ row.weight }}
</template>
</el-table-column>
<el-table-column align="center" label="体积(m^3)" min-width="80">
<template #default="{ row }">
{{ row.volume }}
</template>
</el-table-column>
<template v-if="formData!.subCommissionType">
<el-table-column align="center" label="一级返佣(元)" min-width="80">
<template #default="{ row }">
{{ row.firstBrokeragePrice }}
</template>
</el-table-column>
<el-table-column align="center" label="二级返佣(元)" min-width="80">
<template #default="{ row }">
{{ row.secondBrokeragePrice }}
</template>
</el-table-column>
</template>
</el-table>
<!-- 情况三:作为活动组件 -->
<el-table
v-if="isActivityComponent"
:data="formData!.skus!"
border
max-height="500"
size="small"
style="width: 99%"
>
<el-table-column v-if="isComponent" type="selection" width="45" />
<el-table-column align="center" label="图片" min-width="80">
<template #default="{ row }">
<el-image :src="row.picUrl" class="h-60px w-60px" @click="imagePreview(row.picUrl)" />
</template>
</el-table-column>
<template v-if="formData!.specType">
<!-- 根据商品属性动态添加 -->
<el-table-column
v-for="(item, index) in tableHeaders"
:key="index"
:label="item.label"
align="center"
min-width="80"
>
<template #default="{ row }">
<span style="font-weight: bold; color: #40aaff">
{{ row.properties?.[index]?.valueName }}
</span>
</template>
</el-table-column>
</template>
<el-table-column align="center" label="商品条码" min-width="100">
<template #default="{ row }">
{{ row.barCode }}
</template>
</el-table-column>
<el-table-column align="center" label="销售价(元)" min-width="80">
<template #default="{ row }">
{{ formatToFraction(row.price) }}
</template>
</el-table-column>
<el-table-column align="center" label="市场价(元)" min-width="80">
<template #default="{ row }">
{{ formatToFraction(row.marketPrice) }}
</template>
</el-table-column>
<el-table-column align="center" label="成本价(元)" min-width="80">
<template #default="{ row }">
{{ formatToFraction(row.costPrice) }}
</template>
</el-table-column>
<el-table-column align="center" label="库存" min-width="80">
<template #default="{ row }">
{{ row.stock }}
</template>
</el-table-column>
<!-- 方便扩展每个活动配置的属性不一样 -->
<slot name="extension"></slot>
</el-table>
</template>
<script lang="ts" setup>
import { PropType, Ref } from 'vue'
import { copyValueToTarget, formatToFraction } from '@/utils'
import { propTypes } from '@/utils/propTypes'
import { UploadImg } from '@/components/UploadFile'
import type { Property, Sku, Spu } from '@/api/mall/product/spu'
import { createImageViewer } from '@/components/ImageViewer'
import { RuleConfig } from '@/views/mall/product/spu/components/index'
import { PropertyAndValues } from './index'
import { ElTable } from 'element-plus'
import { isEmpty } from '@/utils/is'
defineOptions({ name: 'SkuList' })
const message = useMessage() // 消息弹窗
const props = defineProps({
propFormData: {
type: Object as PropType<Spu>,
default: () => {}
},
propertyList: {
type: Array as PropType<PropertyAndValues[]>,
default: () => []
},
ruleConfig: {
type: Array as PropType<RuleConfig[]>,
default: () => []
},
isBatch: propTypes.bool.def(false), // 是否作为批量操作组件
isDetail: propTypes.bool.def(false), // 是否作为 sku 详情组件
isComponent: propTypes.bool.def(false), // 是否作为 sku 选择组件
isActivityComponent: propTypes.bool.def(false) // 是否作为 sku 活动配置组件
})
const formData: Ref<Spu | undefined> = ref<Spu>() // 表单数据
const skuList = ref<Sku[]>([
{
price: 0, // 商品价格
marketPrice: 0, // 市场价
costPrice: 0, // 成本价
barCode: '', // 商品条码
picUrl: '', // 图片地址
stock: 0, // 库存
weight: 0, // 商品重量
volume: 0, // 商品体积
firstBrokeragePrice: 0, // 一级分销的佣金
secondBrokeragePrice: 0 // 二级分销的佣金
}
]) // 批量添加时的临时数据
/** 商品图预览 */
const imagePreview = (imgUrl: string) => {
createImageViewer({
zIndex: 9999999,
urlList: [imgUrl]
})
}
/** 批量添加 */
const batchAdd = () => {
validateProperty()
formData.value!.skus!.forEach((item) => {
copyValueToTarget(item, skuList.value[0])
})
}
/** 校验商品属性属性值 */
const validateProperty = () => {
// 校验商品属性属性值是否为空,有一个为空都不给过
const warningInfo = '存在属性属性值为空,请先检查完善属性值后重试!!!'
for (const item of props.propertyList) {
if (!item.values || isEmpty(item.values)) {
message.warning(warningInfo)
throw new Error(warningInfo)
}
}
}
/** 删除 sku */
const deleteSku = (row) => {
const index = formData.value!.skus!.findIndex(
// 直接把列表转成字符串比较
(sku) => JSON.stringify(sku.properties) === JSON.stringify(row.properties)
)
formData.value!.skus!.splice(index, 1)
}
const tableHeaders = ref<{ prop: string; label: string }[]>([]) // 多属性表头
/**
* 保存时,每个商品规格的表单要校验下。例如说,销售金额最低是 0.01 这种。
*/
const validateSku = () => {
validateProperty()
let warningInfo = '请检查商品各行相关属性配置,'
let validate = true // 默认通过
for (const sku of formData.value!.skus!) {
// 作为活动组件的校验
for (const rule of props?.ruleConfig) {
const arg = getValue(sku, rule.name)
if (!rule.rule(arg)) {
validate = false // 只要有一个不通过则直接不通过
warningInfo += rule.message
break
}
}
// 只要有一个不通过则结束后续的校验
if (!validate) {
message.warning(warningInfo)
throw new Error(warningInfo)
}
}
}
const getValue = (obj, arg) => {
const keys = arg.split('.')
let value = obj
for (const key of keys) {
if (value && typeof value === 'object' && key in value) {
value = value[key]
} else {
value = undefined
break
}
}
return value
}
const emit = defineEmits<{
(e: 'selectionChange', value: Sku[]): void
}>()
/**
* 选择时触发
* @param Sku 传递过来的选中的 sku 是一个数组
*/
const handleSelectionChange = (val: Sku[]) => {
emit('selectionChange', val)
}
/**
* 将传进来的值赋值给 skuList
*/
watch(
() => props.propFormData,
(data) => {
if (!data) return
formData.value = data
},
{
deep: true,
immediate: true
}
)
/** 生成表数据 */
const generateTableData = (propertyList: any[]) => {
// 构建数据结构
const propertyValues = propertyList.map((item) =>
item.values.map((v: any) => ({
propertyId: item.id,
propertyName: item.name,
valueId: v.id,
valueName: v.name
}))
)
const buildSkuList = build(propertyValues)
// 如果回显的 sku 属性和添加的属性不一致则重置 skus 列表
if (!validateData(propertyList)) {
// 如果不一致则重置表数据,默认添加新的属性重新生成 sku 列表
formData.value!.skus = []
}
for (const item of buildSkuList) {
const row = {
properties: Array.isArray(item) ? item : [item], // 如果只有一个属性的话返回的是一个 property 对象
price: 0,
marketPrice: 0,
costPrice: 0,
barCode: '',
picUrl: '',
stock: 0,
weight: 0,
volume: 0,
firstBrokeragePrice: 0,
secondBrokeragePrice: 0
}
// 如果存在属性相同的 sku 则不做处理
const index = formData.value!.skus!.findIndex(
(sku) => JSON.stringify(sku.properties) === JSON.stringify(row.properties)
)
if (index !== -1) {
continue
}
formData.value!.skus!.push(row)
}
}
/**
* 生成 skus 前置校验
*/
const validateData = (propertyList: any[]) => {
const skuPropertyIds: number[] = []
formData.value!.skus!.forEach((sku) =>
sku.properties
?.map((property) => property.propertyId)
?.forEach((propertyId) => {
if (skuPropertyIds.indexOf(propertyId!) === -1) {
skuPropertyIds.push(propertyId!)
}
})
)
const propertyIds = propertyList.map((item) => item.id)
return skuPropertyIds.length === propertyIds.length
}
/** 构建所有排列组合 */
const build = (propertyValuesList: Property[][]) => {
if (propertyValuesList.length === 0) {
return []
} else if (propertyValuesList.length === 1) {
return propertyValuesList[0]
} else {
const result: Property[][] = []
const rest = build(propertyValuesList.slice(1))
for (let i = 0; i < propertyValuesList[0].length; i++) {
for (let j = 0; j < rest.length; j++) {
// 第一次不是数组结构,后面的都是数组结构
if (Array.isArray(rest[j])) {
result.push([propertyValuesList[0][i], ...rest[j]])
} else {
result.push([propertyValuesList[0][i], rest[j]])
}
}
}
return result
}
}
/** 监听属性列表,生成相关参数和表头 */
watch(
() => props.propertyList,
(propertyList: PropertyAndValues[]) => {
// 如果不是多规格则结束
if (!formData.value!.specType) {
return
}
// 如果当前组件作为批量添加数据使用,则重置表数据
if (props.isBatch) {
skuList.value = [
{
price: 0,
marketPrice: 0,
costPrice: 0,
barCode: '',
picUrl: '',
stock: 0,
weight: 0,
volume: 0,
firstBrokeragePrice: 0,
secondBrokeragePrice: 0
}
]
}
// 判断代理对象是否为空
if (JSON.stringify(propertyList) === '[]') {
return
}
// 重置表头
tableHeaders.value = []
// 生成表头
propertyList.forEach((item, index) => {
// name加属性项index区分属性值
tableHeaders.value.push({ prop: `name${index}`, label: item.name })
})
// 如果回显的 sku 属性和添加的属性一致则不处理
if (validateData(propertyList)) {
return
}
// 添加新属性没有属性值也不做处理
if (propertyList.some((item) => !item.values || isEmpty(item.values))) {
return
}
// 生成 table 数据,即 sku 列表
generateTableData(propertyList)
},
{
deep: true,
immediate: true
}
)
const activitySkuListRef = ref<InstanceType<typeof ElTable>>()
const getSkuTableRef = () => {
return activitySkuListRef.value
}
// 暴露出生成 sku 方法,给添加属性成功时调用
defineExpose({ generateTableData, validateSku, getSkuTableRef })
</script>
@@ -0,0 +1,95 @@
<template>
<Dialog v-model="dialogVisible" :appendToBody="true" title="选择规格" width="700">
<el-table v-loading="loading" :data="list" show-overflow-tooltip>
<el-table-column label="#" width="55">
<template #default="{ row }">
<el-radio :value="row.id" v-model="selectedSkuId" @change="handleSelected(row)"
>&nbsp;
</el-radio>
</template>
</el-table-column>
<el-table-column label="图片" min-width="80">
<template #default="{ row }">
<el-image
:src="row.picUrl"
class="h-30px w-30px"
:preview-src-list="[row.picUrl]"
preview-teleported
/>
</template>
</el-table-column>
<el-table-column label="规格" align="center" min-width="80">
<template #default="{ row }">
{{ row.properties?.map((p) => p.valueName)?.join(' ') }}
</template>
</el-table-column>
<el-table-column align="center" label="销售价(元)" min-width="80">
<template #default="{ row }">
{{ fenToYuan(row.price) }}
</template>
</el-table-column>
</el-table>
</Dialog>
</template>
<script lang="ts" setup>
import { ElTable } from 'element-plus'
import * as ProductSpuApi from '@/api/mall/product/spu'
import { propTypes } from '@/utils/propTypes'
import { fenToYuan } from '@/utils'
defineOptions({ name: 'SkuTableSelect' })
const props = defineProps({
spuId: propTypes.number.def(null)
})
const message = useMessage() // 消息弹窗
const list = ref<any[]>([]) // 列表的数据
const loading = ref(false) // 列表的加载中
const dialogVisible = ref(false) // 弹窗的是否展示
const selectedSkuId = ref() // 选中的商品 spuId
/** 选中时触发 */
const handleSelected = (row: ProductSpuApi.Sku) => {
emits('change', row)
// 关闭弹窗
dialogVisible.value = false
selectedSkuId.value = undefined
}
// 确认选择时的触发事件
const emits = defineEmits<{
(e: 'change', spu: ProductSpuApi.Sku): void
}>()
/** 打开弹窗 */
const open = () => {
dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法,用于打开弹窗
/** 查询列表 */
const getSpuDetail = async () => {
loading.value = true
try {
const spu = await ProductSpuApi.getSpu(props.spuId)
list.value = spu.skus
} finally {
loading.value = false
}
}
/** 初始化 **/
onMounted(async () => {})
watch(
() => props.spuId,
() => {
if (!props.spuId) {
return
}
getSpuDetail()
}
)
</script>
@@ -0,0 +1,144 @@
<template>
<div class="flex flex-wrap items-center gap-8px">
<div v-for="(spu, index) in productSpus" :key="spu.id" class="select-box spu-pic">
<el-tooltip :content="spu.name">
<div class="relative h-full w-full">
<el-image :src="spu.picUrl" class="h-full w-full" />
<Icon
v-show="!disabled"
class="del-icon"
icon="ep:circle-close-filled"
@click="handleRemoveSpu(index)"
/>
</div>
</el-tooltip>
</div>
<el-tooltip content="选择商品" v-if="canAdd">
<div class="select-box" @click="openSpuTableSelect">
<Icon icon="ep:plus" />
</div>
</el-tooltip>
</div>
<!-- 商品选择对话框(表格形式) -->
<SpuTableSelect ref="spuTableSelectRef" :multiple="limit != 1" @change="handleSpuSelected" />
</template>
<script lang="ts" setup>
import * as ProductSpuApi from '@/api/mall/product/spu'
import SpuTableSelect from '@/views/mall/product/spu/components/SpuTableSelect.vue'
import { propTypes } from '@/utils/propTypes'
import { oneOfType } from 'vue-types'
import { isArray } from '@/utils/is'
// 商品橱窗,一般用于与商品建立关系时使用
// 提供功能:展示商品列表、添加商品、移除商品
defineOptions({ name: 'SpuShowcase' })
const props = defineProps({
modelValue: oneOfType<number | Array<number>>([Number, Array]).isRequired,
// 限制数量:默认不限制
limit: propTypes.number.def(Number.MAX_VALUE),
disabled: propTypes.bool.def(false)
})
// 计算是否可以添加
const canAdd = computed(() => {
// 情况一:禁用时不可以添加
if (props.disabled) return false
// 情况二:未指定限制数量时,可以添加
if (!props.limit) return true
// 情况三:检查已添加数量是否小于限制数量
return productSpus.value.length < props.limit
})
// 商品列表
const productSpus = ref<ProductSpuApi.Spu[]>([])
watch(
() => props.modelValue,
async () => {
const ids = isArray(props.modelValue)
? // 情况一:多选
props.modelValue
: // 情况二:单选
props.modelValue
? [props.modelValue]
: []
// 不需要返显
if (ids.length === 0) {
productSpus.value = []
return
}
// 只有商品发生变化之后,才去查询商品
if (productSpus.value.length === 0 || productSpus.value.some((spu) => !ids.includes(spu.id!))) {
productSpus.value = await ProductSpuApi.getSpuDetailList(ids)
}
},
{ immediate: true }
)
/** 商品表格选择对话框 */
const spuTableSelectRef = ref()
// 打开对话框
const openSpuTableSelect = () => {
spuTableSelectRef.value.open(productSpus.value)
}
/**
* 选择商品后触发
*
* @param spus 选中的商品列表
*/
const handleSpuSelected = (spus: ProductSpuApi.Spu | ProductSpuApi.Spu[]) => {
productSpus.value = isArray(spus) ? spus : [spus]
emitSpuChange()
}
/**
* 删除商品
*
* @param index 商品索引
*/
const handleRemoveSpu = (index: number) => {
productSpus.value.splice(index, 1)
emitSpuChange()
}
const emit = defineEmits(['update:modelValue', 'change'])
const emitSpuChange = () => {
if (props.limit === 1) {
const spu = productSpus.value.length > 0 ? productSpus.value[0] : null
emit('update:modelValue', spu?.id || 0)
emit('change', spu)
} else {
emit(
'update:modelValue',
productSpus.value.map((spu) => spu.id)
)
emit('change', productSpus.value)
}
}
</script>
<style lang="scss" scoped>
.select-box {
display: flex;
width: 60px;
height: 60px;
border: 1px dashed var(--el-border-color-darker);
border-radius: 8px;
align-items: center;
justify-content: center;
}
.spu-pic {
position: relative;
}
.del-icon {
position: absolute;
top: -10px;
right: -10px;
z-index: 1;
width: 20px !important;
height: 20px !important;
}
</style>
@@ -0,0 +1,303 @@
<template>
<Dialog v-model="dialogVisible" :appendToBody="true" title="选择商品" width="70%">
<ContentWrap>
<el-form
ref="queryFormRef"
:inline="true"
:model="queryParams"
class="-mb-15px"
label-width="68px"
>
<el-form-item label="商品名称" prop="name">
<el-input
v-model="queryParams.name"
class="!w-240px"
clearable
placeholder="请输入商品名称"
@keyup.enter="handleQuery"
/>
</el-form-item>
<el-form-item label="商品分类" prop="categoryId">
<el-tree-select
v-model="queryParams.categoryId"
:data="categoryTreeList"
:props="defaultProps"
check-strictly
class="!w-240px"
node-key="id"
placeholder="请选择商品分类"
/>
</el-form-item>
<el-form-item label="创建时间" prop="createTime">
<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-form-item>
<el-form-item>
<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-form-item>
</el-form>
<el-table v-loading="loading" :data="list" show-overflow-tooltip>
<!-- 1. 多选模式(不能使用type="selection",Element会忽略Header插槽) -->
<el-table-column width="55" v-if="multiple">
<template #header>
<el-checkbox
v-model="isCheckAll"
:indeterminate="isIndeterminate"
@change="handleCheckAll"
/>
</template>
<template #default="{ row }">
<el-checkbox
v-model="checkedStatus[row.id]"
@change="(checked: boolean) => handleCheckOne(checked, row, true)"
/>
</template>
</el-table-column>
<!-- 2. 单选模式 -->
<el-table-column label="#" width="55" v-else>
<template #default="{ row }">
<el-radio :value="row.id" v-model="selectedSpuId" @change="handleSingleSelected(row)">
<!-- 空格不能省略,是为了让单选框不显示label,如果不指定label不会有选中的效果 -->
&nbsp;
</el-radio>
</template>
</el-table-column>
<el-table-column key="id" align="center" label="商品编号" prop="id" min-width="60" />
<el-table-column label="商品图" min-width="80">
<template #default="{ row }">
<el-image
:src="row.picUrl"
class="h-30px w-30px"
:preview-src-list="[row.picUrl]"
preview-teleported
/>
</template>
</el-table-column>
<el-table-column label="商品名称" min-width="200" prop="name" />
<el-table-column label="商品分类" min-width="100" prop="categoryId">
<template #default="{ row }">
<span>{{ categoryList?.find((c) => c.id === row.categoryId)?.name }}</span>
</template>
</el-table-column>
</el-table>
<!-- 分页 -->
<Pagination
v-model:limit="queryParams.pageSize"
v-model:page="queryParams.pageNo"
:total="total"
@pagination="getList"
/>
</ContentWrap>
<template #footer v-if="multiple">
<el-button type="primary" @click="handleEmitChange">确 定</el-button>
<el-button @click="dialogVisible = false">取 消</el-button>
</template>
</Dialog>
</template>
<script lang="ts" setup>
import { 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'
import { CHANGE_EVENT } from 'element-plus'
type Spu = Required<ProductSpuApi.Spu>
/**
* 商品表格选择对话框
* 1. 单选模式:
* 1.1 点击表格左侧的单选框时,结束选择,并关闭对话框
* 1.2 再次打开时,保持选中状态
* 2. 多选模式:
* 2.1 点击表格左侧的多选框时,记录选中的商品
* 2.2 切换分页时,保持商品的选中的状态
* 2.3 点击右下角的确定按钮时,结束选择,关闭对话框
* 2.4 再次打开时,保持选中状态
*/
defineOptions({ name: 'SpuTableSelect' })
defineProps({
// 多选模式
multiple: propTypes.bool.def(false)
})
// 列表的总页数
const total = ref(0)
// 列表的数据
const list = ref<Spu[]>([])
// 列表的加载中
const loading = ref(false)
// 弹窗的是否展示
const dialogVisible = ref(false)
// 查询参数
const queryParams = ref({
pageNo: 1,
pageSize: 10,
// 默认获取上架的商品
tabType: 0,
name: '',
categoryId: null,
createTime: []
})
/** 打开弹窗 */
const open = (spuList?: Spu[]) => {
// 重置
checkedSpus.value = []
checkedStatus.value = {}
isCheckAll.value = false
isIndeterminate.value = false
// 处理已选中
if (spuList && spuList.length > 0) {
checkedSpus.value = [...spuList]
checkedStatus.value = Object.fromEntries(spuList.map((spu) => [spu.id, true]))
}
dialogVisible.value = true
resetQuery()
}
// 提供 open 方法,用于打开弹窗
defineExpose({ open })
/** 查询列表 */
const getList = async () => {
loading.value = true
try {
const data = await ProductSpuApi.getSpuPage(queryParams.value)
list.value = data.list
total.value = data.total
// checkbox绑定undefined会有问题,需要给一个bool值
list.value.forEach(
(spu) => (checkedStatus.value[spu.id] = checkedStatus.value[spu.id] || false)
)
// 计算全选框状态
calculateIsCheckAll()
} finally {
loading.value = false
}
}
/** 搜索按钮操作 */
const handleQuery = () => {
queryParams.value.pageNo = 1
getList()
}
/** 重置按钮操作 */
const resetQuery = () => {
queryParams.value = {
pageNo: 1,
pageSize: 10,
// 默认获取上架的商品
tabType: 0,
name: '',
categoryId: null,
createTime: []
}
getList()
}
// 是否全选
const isCheckAll = ref(false)
// 全选框是否处于中间状态:不是全部选中 && 任意一个选中
const isIndeterminate = ref(false)
// 选中的商品
const checkedSpus = ref<Spu[]>([])
// 选中状态:key为商品ID,value为是否选中
const checkedStatus = ref<Record<string, boolean>>({})
// 选中的商品 spuId
const selectedSpuId = ref()
/** 单选中时触发 */
const handleSingleSelected = (spu: Spu) => {
emits(CHANGE_EVENT, spu)
// 关闭弹窗
dialogVisible.value = false
// 记住上次选择的ID
selectedSpuId.value = spu.id
}
/** 多选完成 */
const handleEmitChange = () => {
// 关闭弹窗
dialogVisible.value = false
emits(CHANGE_EVENT, [...checkedSpus.value])
}
/** 确认选择时的触发事件 */
const emits = defineEmits<{
change: [spu: Spu | Spu[] | any]
}>()
/** 全选/全不选 */
const handleCheckAll = (checked: boolean) => {
isCheckAll.value = checked
isIndeterminate.value = false
list.value.forEach((spu) => handleCheckOne(checked, spu, false))
}
/**
* 选中一行
* @param checked 是否选中
* @param spu 商品
* @param isCalcCheckAll 是否计算全选
*/
const handleCheckOne = (checked: boolean, spu: Spu, isCalcCheckAll: boolean) => {
if (checked) {
checkedSpus.value.push(spu)
checkedStatus.value[spu.id] = true
} else {
const index = findCheckedIndex(spu)
if (index > -1) {
checkedSpus.value.splice(index, 1)
checkedStatus.value[spu.id] = false
isCheckAll.value = false
}
}
// 计算全选框状态
if (isCalcCheckAll) {
calculateIsCheckAll()
}
}
// 查找商品在已选中商品列表中的索引
const findCheckedIndex = (spu: Spu) => checkedSpus.value.findIndex((item) => item.id === spu.id)
// 计算全选框状态
const calculateIsCheckAll = () => {
isCheckAll.value = list.value.every((spu) => checkedStatus.value[spu.id])
// 计算中间状态:不是全部选中 && 任意一个选中
isIndeterminate.value = !isCheckAll.value && list.value.some((spu) => checkedStatus.value[spu.id])
}
// 分类列表
const categoryList = ref()
// 分类树
const categoryTreeList = ref()
/** 初始化 **/
onMounted(async () => {
await getList()
// 获得分类树
categoryList.value = await ProductCategoryApi.getCategoryList({})
categoryTreeList.value = handleTree(categoryList.value, 'id', 'parentId')
})
</script>
@@ -0,0 +1,54 @@
import SkuList from './SkuList.vue'
import { Spu } from '@/api/mall/product/spu'
interface PropertyAndValues {
id: number
name: string
values?: PropertyAndValues[]
}
interface RuleConfig {
// 需要校验的字段
// 例:name: 'name' 则表示校验 sku.name 的值
// 例:name: 'productConfig.stock' 则表示校验 sku.productConfig.name 的值,此处 productConfig 表示我在 Sku 上扩展的属性
name: string
// 校验规格为一个毁掉函数,其中 arg 为需要校验的字段的值。
// 例:需要校验价格必须大于0.01
// {
// name:'price',
// rule:(arg: number) => arg > 0.01
// }
rule: (arg: any) => boolean
// 校验不通过时的消息提示
message: string
}
/**
* 获得商品的规格列表 - 商品相关的公共函数
*
* @param spu
* @return PropertyAndValues 规格列表
*/
const getPropertyList = (spu: Spu): PropertyAndValues[] => {
// 直接拿返回的 skus 属性逆向生成出 propertyList
const properties: PropertyAndValues[] = []
// 只有是多规格才处理
if (spu.specType) {
spu.skus?.forEach((sku) => {
sku.properties?.forEach(({ propertyId, propertyName, valueId, valueName }) => {
// 添加属性
if (!properties?.some((item) => item.id === propertyId)) {
properties.push({ id: propertyId!, name: propertyName!, values: [] })
}
// 添加属性值
const index = properties?.findIndex((item) => item.id === propertyId)
if (!properties[index].values?.some((value) => value.id === valueId)) {
properties[index].values?.push({ id: valueId!, name: valueName! })
}
})
})
}
return properties
}
export { SkuList, PropertyAndValues, RuleConfig, getPropertyList }
@@ -0,0 +1,96 @@
<!-- 商品发布 - 物流设置 -->
<template>
<el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" :disabled="isDetail">
<el-form-item label="配送方式" prop="deliveryTypes">
<el-checkbox-group v-model="formData.deliveryTypes" class="w-80">
<el-checkbox
v-for="dict in getIntDictOptions(DICT_TYPE.TRADE_DELIVERY_TYPE)"
:key="dict.value"
:value="dict.value"
>
{{ dict.label }}
</el-checkbox>
</el-checkbox-group>
</el-form-item>
<el-form-item
label="运费模板"
prop="deliveryTemplateId"
v-if="formData.deliveryTypes?.includes(DeliveryTypeEnum.EXPRESS.type)"
>
<el-select placeholder="请选择运费模板" v-model="formData.deliveryTemplateId" class="w-80">
<el-option
v-for="item in deliveryTemplateList"
:key="item.id"
:label="item.name"
:value="item.id"
/>
</el-select>
</el-form-item>
</el-form>
</template>
<script lang="ts" setup>
import { PropType } from 'vue'
import { copyValueToTarget } from '@/utils'
import { propTypes } from '@/utils/propTypes'
import type { Spu } from '@/api/mall/product/spu'
import * as ExpressTemplateApi from '@/api/mall/trade/delivery/expressTemplate'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { DeliveryTypeEnum } from '@/utils/constants'
defineOptions({ name: 'ProductDeliveryForm' })
const message = useMessage() // 消息弹窗
const props = defineProps({
propFormData: {
type: Object as PropType<Spu>,
default: () => {}
},
isDetail: propTypes.bool.def(false) // 是否作为详情组件
})
const formRef = ref() // 表单 Ref
const formData = reactive<Spu>({
deliveryTypes: [], // 配送方式
deliveryTemplateId: undefined // 运费模版
})
const rules = reactive({
deliveryTypes: [required],
deliveryTemplateId: [required]
})
/** 将传进来的值赋值给 formData */
watch(
() => props.propFormData,
(data) => {
if (!data) {
return
}
copyValueToTarget(formData, data)
},
{
immediate: true
}
)
/** 表单校验 */
const emit = defineEmits(['update:activeName'])
const validate = async () => {
if (!formRef) return
try {
await unref(formRef)?.validate()
// 校验通过更新数据
Object.assign(props.propFormData, formData)
} catch (e) {
message.error('【物流设置】不完善,请填写相关信息')
emit('update:activeName', 'delivery')
throw e // 目的截断之后的校验
}
}
defineExpose({ validate })
/** 初始化 */
const deliveryTemplateList = ref([]) // 运费模版
onMounted(async () => {
deliveryTemplateList.value = await ExpressTemplateApi.getSimpleTemplateList()
})
</script>
@@ -0,0 +1,81 @@
<!-- 商品发布 - 商品详情 -->
<template>
<el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" :disabled="isDetail">
<!--富文本编辑器组件-->
<el-form-item label="商品详情" prop="description">
<Editor v-model:modelValue="formData.description" />
</el-form-item>
</el-form>
</template>
<script lang="ts" setup>
import type { Spu } from '@/api/mall/product/spu'
import { Editor } from '@/components/Editor'
import { PropType } from 'vue'
import { propTypes } from '@/utils/propTypes'
import { copyValueToTarget } from '@/utils'
defineOptions({ name: 'ProductDescriptionForm' })
const message = useMessage() // 消息弹窗
const props = defineProps({
propFormData: {
type: Object as PropType<Spu>,
default: () => {}
},
activeName: propTypes.string.def(''),
isDetail: propTypes.bool.def(false) // 是否作为详情组件
})
const formRef = ref() // 表单Ref
const formData = ref<Spu>({
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
// fix:三个表单组件监听赋值必须使用 copyValueToTarget 使用 formData.value = data 会监听非常多次
copyValueToTarget(formData.value, data)
},
{
// fix: 去掉深度监听只有对象引用发生改变的时候才执行,解决改一动多的问题
immediate: true
}
)
/** 表单校验 */
const emit = defineEmits(['update:activeName'])
const validate = async () => {
if (!formRef) return
try {
await unref(formRef)?.validate()
// 校验通过更新数据
Object.assign(props.propFormData, formData.value)
} catch (e) {
message.error('【商品详情】不完善,请填写相关信息')
emit('update:activeName', 'description')
throw e // 目的截断之后的校验
}
}
defineExpose({ validate })
</script>
@@ -0,0 +1,142 @@
<!-- 商品发布 - 基础设置 -->
<template>
<el-form ref="formRef" :disabled="isDetail" :model="formData" :rules="rules" label-width="120px">
<el-form-item label="商品名称" prop="name">
<el-input
v-model="formData.name"
:autosize="{ minRows: 2, maxRows: 2 }"
:clearable="true"
:show-word-limit="true"
class="w-80!"
maxlength="64"
placeholder="请输入商品名称"
type="textarea"
/>
</el-form-item>
<el-form-item label="商品分类" prop="categoryId">
<el-cascader
v-model="formData.categoryId"
:options="categoryList"
:props="defaultProps"
class="w-80"
clearable
filterable
placeholder="请选择商品分类"
/>
</el-form-item>
<el-form-item label="商品品牌" prop="brandId">
<el-select v-model="formData.brandId" class="w-80" placeholder="请选择商品品牌">
<el-option
v-for="item in brandList"
:key="item.id"
:label="item.name"
:value="item.id as number"
/>
</el-select>
</el-form-item>
<el-form-item label="商品关键字" prop="keyword">
<el-input v-model="formData.keyword" class="w-80!" placeholder="请输入商品关键字" />
</el-form-item>
<el-form-item label="商品简介" prop="introduction">
<el-input
v-model="formData.introduction"
:autosize="{ minRows: 2, maxRows: 2 }"
:clearable="true"
:show-word-limit="true"
class="w-80!"
maxlength="128"
placeholder="请输入商品简介"
type="textarea"
/>
</el-form-item>
<el-form-item label="商品封面图" prop="picUrl">
<UploadImg v-model="formData.picUrl" :disabled="isDetail" height="80px" />
</el-form-item>
<el-form-item label="商品轮播图" prop="sliderPicUrls">
<UploadImgs v-model="formData.sliderPicUrls" :disabled="isDetail" />
</el-form-item>
</el-form>
</template>
<script lang="ts" setup>
import { PropType } from 'vue'
import { copyValueToTarget } from '@/utils'
import { propTypes } from '@/utils/propTypes'
import { defaultProps, handleTree } from '@/utils/tree'
import type { Spu } from '@/api/mall/product/spu'
import * as ProductCategoryApi from '@/api/mall/product/category'
import { CategoryVO } from '@/api/mall/product/category'
import * as ProductBrandApi from '@/api/mall/product/brand'
import { BrandVO } from '@/api/mall/product/brand'
defineOptions({ name: 'ProductSpuInfoForm' })
const props = defineProps({
propFormData: {
type: Object as PropType<Spu>,
default: () => {}
},
isDetail: propTypes.bool.def(false) // 是否作为详情组件
})
const message = useMessage() // 消息弹窗
const formRef = ref() // 表单 Ref
const formData = reactive<Spu>({
name: '', // 商品名称
categoryId: undefined, // 商品分类
keyword: '', // 关键字
picUrl: '', // 商品封面图
sliderPicUrls: [], // 商品轮播图
introduction: '', // 商品简介
brandId: undefined // 商品品牌
})
const rules = reactive({
name: [required],
categoryId: [required],
keyword: [required],
introduction: [required],
picUrl: [required],
sliderPicUrls: [required],
brandId: [required]
})
/** 将传进来的值赋值给 formData */
watch(
() => props.propFormData,
(data) => {
if (!data) {
return
}
copyValueToTarget(formData, data)
},
{
immediate: true
}
)
/** 表单校验 */
const emit = defineEmits(['update:activeName'])
const validate = async () => {
if (!formRef) return
try {
await unref(formRef)?.validate()
// 校验通过更新数据
Object.assign(props.propFormData, formData)
} catch (e) {
message.error('【基础设置】不完善,请填写相关信息')
emit('update:activeName', 'info')
throw e // 目的截断之后的校验
}
}
defineExpose({ validate })
/** 初始化 */
const brandList = ref<BrandVO[]>([]) // 商品品牌列表
const categoryList = ref<CategoryVO[]>([]) // 商品分类树
onMounted(async () => {
// 获得分类树
const data = await ProductCategoryApi.getCategoryList({})
categoryList.value = handleTree(data, 'id')
// 获取商品品牌列表
brandList.value = await ProductBrandApi.getSimpleBrandList()
})
</script>
@@ -0,0 +1,91 @@
<!-- 商品发布 - 其它设置 -->
<template>
<el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" :disabled="isDetail">
<el-form-item label="商品排序" prop="sort">
<el-input-number
v-model="formData.sort"
:min="0"
placeholder="请输入商品排序"
class="w-80!"
/>
</el-form-item>
<el-form-item label="赠送积分" prop="giveIntegral">
<el-input-number
v-model="formData.giveIntegral"
:min="0"
placeholder="请输入赠送积分"
class="w-80!"
/>
</el-form-item>
<el-form-item label="虚拟销量" prop="virtualSalesCount">
<el-input-number
v-model="formData.virtualSalesCount"
:min="0"
placeholder="请输入虚拟销量"
class="w-80!"
/>
</el-form-item>
</el-form>
</template>
<script lang="ts" setup>
import type { Spu } from '@/api/mall/product/spu'
import { PropType } from 'vue'
import { propTypes } from '@/utils/propTypes'
import { copyValueToTarget } from '@/utils'
defineOptions({ name: 'ProductOtherForm' })
const message = useMessage() // 消息弹窗
const props = defineProps({
propFormData: {
type: Object as PropType<Spu>,
default: () => {}
},
isDetail: propTypes.bool.def(false) // 是否作为详情组件
})
const formRef = ref() // 表单Ref
// 表单数据
const formData = ref<Spu>({
sort: 0, // 商品排序
giveIntegral: 0, // 赠送积分
virtualSalesCount: 0 // 虚拟销量
})
// 表单规则
const rules = reactive({
sort: [required],
giveIntegral: [required],
virtualSalesCount: [required]
})
/** 将传进来的值赋值给 formData */
watch(
() => props.propFormData,
(data) => {
if (!data) {
return
}
copyValueToTarget(formData.value, data)
},
{
immediate: true
}
)
/** 表单校验 */
const emit = defineEmits(['update:activeName'])
const validate = async () => {
if (!formRef) return
try {
await unref(formRef)?.validate()
// 校验通过更新数据
Object.assign(props.propFormData, formData.value)
} catch (e) {
message.error('【其它设置】不完善,请填写相关信息')
emit('update:activeName', 'other')
throw e // 目的截断之后的校验
}
}
defineExpose({ validate })
</script>
@@ -0,0 +1,162 @@
<!-- 商品发布 - 库存价格 - 属性列表 -->
<template>
<el-col v-for="(item, index) in attributeList" :key="index">
<div>
<el-text class="mx-1">属性名:</el-text>
<el-tag :closable="!isDetail" class="mx-1" type="success" @close="handleCloseProperty(index)">
{{ item.name }}
</el-tag>
</div>
<div>
<el-text class="mx-1">属性值:</el-text>
<el-tag
v-for="(value, valueIndex) in item.values"
:key="value.id"
:closable="!isDetail"
class="mx-1"
@close="handleCloseValue(index, valueIndex)"
>
{{ value.name }}
</el-tag>
<el-select
v-show="inputVisible(index)"
:id="`input${index}`"
:ref="setInputRef"
v-model="inputValue"
:reserve-keyword="false"
allow-create
class="!w-30"
default-first-option
filterable
size="small"
@blur="handleInputConfirm(index, item.id)"
@change="handleInputConfirm(index, item.id)"
@keyup.enter="handleInputConfirm(index, item.id)"
>
<el-option
v-for="item2 in attributeOptions"
:key="item2.id"
:label="item2.name"
:value="item2.name"
/>
</el-select>
<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" setup>
import * as PropertyApi from '@/api/mall/product/property'
import { PropertyAndValues } from '@/views/mall/product/spu/components'
import { propTypes } from '@/utils/propTypes'
defineOptions({ name: 'ProductAttributes' })
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const inputValue = ref('') // 输入框值
const attributeIndex = ref<number | null>(null) // 获取焦点时记录当前属性项的index
// 输入框显隐控制
const inputVisible = computed(() => (index: number) => {
if (attributeIndex.value === null) return false
if (attributeIndex.value === index) return true
})
const inputRef = ref<any[]>([]) //标签输入框Ref
/** 解决 ref 在 v-for 中的获取问题*/
const setInputRef = (el: any) => {
if (el === null || typeof el === 'undefined') return
// 如果不存在 id 相同的元素才添加
if (!inputRef.value.some((item) => item.inputRef?.attributes.id === el.inputRef?.attributes.id)) {
inputRef.value.push(el)
}
}
const attributeList = ref<PropertyAndValues[]>([]) // 商品属性列表
const attributeOptions = ref([] as PropertyApi.PropertyValueVO[]) // 商品属性名称下拉框
const props = defineProps({
propertyList: {
type: Array,
default: () => {}
},
isDetail: propTypes.bool.def(false) // 是否作为详情组件
})
watch(
() => props.propertyList,
(data) => {
if (!data) return
attributeList.value = data as any
},
{
deep: true,
immediate: true
}
)
/** 删除属性值*/
const handleCloseValue = (index: number, valueIndex: number) => {
attributeList.value[index].values?.splice(valueIndex, 1)
}
/** 删除属性*/
const handleCloseProperty = (index: number) => {
attributeList.value?.splice(index, 1)
emit('success', attributeList.value)
}
/** 显示输入框并获取焦点 */
const showInput = async (index: number) => {
attributeIndex.value = index
inputRef.value[index].focus()
// 获取属性下拉选项
await getAttributeOptions(attributeList.value[index].id)
}
/** 输入框失去焦点或点击回车时触发 */
const emit = defineEmits(['success']) // 定义 success 事件,用于操作成功后的回调
const handleInputConfirm = async (index: number, propertyId: number) => {
if (inputValue.value) {
// 1. 重复添加校验
if (attributeList.value[index].values.find((item) => item.name === inputValue.value)) {
message.warning('已存在相同属性值,请重试')
attributeIndex.value = null
inputValue.value = ''
return
}
// 2.1 情况一:属性值已存在,则直接使用并结束
const existValue = attributeOptions.value.find((item) => item.name === inputValue.value)
if (existValue) {
attributeIndex.value = null
inputValue.value = ''
attributeList.value[index].values.push({ id: existValue.id, name: existValue.name })
emit('success', attributeList.value)
return
}
// 2.2 情况二:新属性值,则进行保存
try {
const id = await PropertyApi.createPropertyValue({ propertyId, name: inputValue.value })
attributeList.value[index].values.push({ id, name: inputValue.value })
message.success(t('common.createSuccess'))
emit('success', attributeList.value)
} catch {
message.error('添加失败,请重试')
}
}
attributeIndex.value = null
inputValue.value = ''
}
/** 获取商品属性下拉选项 */
const getAttributeOptions = async (propertyId: number) => {
attributeOptions.value = await PropertyApi.getPropertyValueSimpleList(propertyId)
}
</script>
@@ -0,0 +1,148 @@
<!-- 商品发布 - 库存价格 - 添加属性 -->
<template>
<Dialog v-model="dialogVisible" title="添加商品属性">
<el-form
ref="formRef"
v-loading="formLoading"
:model="formData"
:rules="formRules"
label-width="80px"
@keydown.enter.prevent="submitForm"
>
<el-form-item label="属性名称" prop="name">
<el-select
v-model="formData.name"
:reserve-keyword="false"
allow-create
class="!w-360px"
default-first-option
filterable
placeholder="请选择属性名称。如果不存在,可手动输入选择"
>
<el-option
v-for="item in attributeOptions"
:key="item.id"
:label="item.name"
:value="item.name"
/>
</el-select>
</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" setup>
import * as PropertyApi from '@/api/mall/product/property'
defineOptions({ name: 'ProductPropertyForm' })
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const formData = ref({
name: ''
})
const formRules = reactive({
name: [{ required: true, message: '名称不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const attributeList = ref([]) // 商品属性列表
const attributeOptions = ref([] as PropertyApi.PropertyVO[]) // 商品属性名称下拉框
const props = defineProps({
propertyList: {
type: Array,
default: () => {}
}
})
watch(
() => props.propertyList, // 解决 props 无法直接修改父组件的问题
(data) => {
if (!data) return
attributeList.value = data
},
{
deep: true,
immediate: true
}
)
/** 打开弹窗 */
const open = async () => {
dialogVisible.value = true
resetForm()
// 加载列表
await getAttributeOptions()
}
defineExpose({ open }) // 提供 open 方法,用于打开弹窗
/** 提交表单 */
const submitForm = async () => {
// 1.1 重复添加校验
for (const attrItem of attributeList.value) {
if (attrItem.name === formData.value.name) {
return message.error('该属性已存在,请勿重复添加')
}
}
// 1.2 校验表单
if (!formRef) return
const valid = await formRef.value.validate()
if (!valid) return
// 2.1 情况一:属性名已存在,则直接使用并结束
const existProperty = attributeOptions.value.find((item) => item.name === formData.value.name)
if (existProperty) {
// 添加到属性列表
attributeList.value.push({
id: existProperty.id,
...formData.value,
values: []
})
// 关闭弹窗
dialogVisible.value = false
return
}
// 2.2 情况二:如果是不存在的属性,则需要执行新增
// 提交请求
formLoading.value = true
try {
const data = formData.value as PropertyApi.PropertyVO
const propertyId = await PropertyApi.createProperty(data)
// 添加到属性列表
attributeList.value.push({
id: propertyId,
...formData.value,
values: []
})
// 关闭弹窗
message.success(t('common.createSuccess'))
dialogVisible.value = false
} finally {
formLoading.value = false
}
}
/** 重置表单 */
const resetForm = () => {
formData.value = {
name: ''
}
formRef.value?.resetFields()
}
/** 获取商品属性下拉选项 */
const getAttributeOptions = async () => {
formLoading.value = true
try {
attributeOptions.value = await PropertyApi.getPropertySimpleList()
} finally {
formLoading.value = false
}
}
</script>
@@ -0,0 +1,194 @@
<!-- 商品发布 - 库存价格 -->
<template>
<el-form
ref="formRef"
v-loading="formLoading"
:disabled="isDetail"
:model="formData"
:rules="rules"
label-width="120px"
>
<el-form-item label="分销类型" prop="subCommissionType">
<el-radio-group
v-model="formData.subCommissionType"
class="w-80"
@change="changeSubCommissionType"
>
<el-radio :value="false">默认设置</el-radio>
<el-radio :value="true" class="radio">单独设置</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="商品规格" prop="specType">
<el-radio-group v-model="formData.specType" class="w-80" @change="onChangeSpec">
<el-radio :value="false" class="radio">单规格</el-radio>
<el-radio :value="true">多规格</el-radio>
</el-radio-group>
</el-form-item>
<!-- 多规格添加-->
<el-form-item v-if="!formData.specType">
<SkuList
ref="skuListRef"
:prop-form-data="formData"
:property-list="propertyList"
:rule-config="ruleConfig"
/>
</el-form-item>
<el-form-item v-if="formData.specType" label="商品属性">
<el-button class="mb-10px mr-15px" @click="attributesAddFormRef.open">添加属性</el-button>
<ProductAttributes
:is-detail="isDetail"
:property-list="propertyList"
@success="generateSkus"
/>
</el-form-item>
<template v-if="formData.specType && propertyList.length > 0">
<el-form-item v-if="!isDetail" label="批量设置">
<SkuList :is-batch="true" :prop-form-data="formData" :property-list="propertyList" />
</el-form-item>
<el-form-item label="规格列表">
<SkuList
ref="skuListRef"
:is-detail="isDetail"
:prop-form-data="formData"
:property-list="propertyList"
:rule-config="ruleConfig"
/>
</el-form-item>
</template>
</el-form>
<!-- 商品属性添加 Form 表单 -->
<ProductPropertyAddForm ref="attributesAddFormRef" :propertyList="propertyList" />
</template>
<script lang="ts" setup>
import { PropType } from 'vue'
import { copyValueToTarget } from '@/utils'
import { propTypes } from '@/utils/propTypes'
import {
getPropertyList,
PropertyAndValues,
RuleConfig,
SkuList
} from '@/views/mall/product/spu/components/index'
import ProductAttributes from './ProductAttributes.vue'
import ProductPropertyAddForm from './ProductPropertyAddForm.vue'
import type { Spu } from '@/api/mall/product/spu'
defineOptions({ name: 'ProductSpuSkuForm' })
// sku 相关属性校验规则
const ruleConfig: RuleConfig[] = [
{
name: 'stock',
rule: (arg) => arg >= 0,
message: '商品库存必须大于等于 1 !!!'
},
{
name: 'price',
rule: (arg) => arg >= 0.01,
message: '商品销售价格必须大于等于 0.01 元!!!'
},
{
name: 'marketPrice',
rule: (arg) => arg >= 0.01,
message: '商品市场价格必须大于等于 0.01 元!!!'
},
{
name: 'costPrice',
rule: (arg) => arg >= 0.01,
message: '商品成本价格必须大于等于 0.00 元!!!'
}
]
const message = useMessage() // 消息弹窗
const formLoading = ref(false)
const props = defineProps({
propFormData: {
type: Object as PropType<Spu>,
default: () => {}
},
isDetail: propTypes.bool.def(false) // 是否作为详情组件
})
const attributesAddFormRef = ref() // 添加商品属性表单
const formRef = ref() // 表单 Ref
const propertyList = ref<PropertyAndValues[]>([]) // 商品属性列表
const skuListRef = ref() // 商品属性列表 Ref
const formData = reactive<Spu>({
specType: false, // 商品规格
subCommissionType: false, // 分销类型
skus: []
})
const rules = reactive({
specType: [required],
subCommissionType: [required]
})
/** 将传进来的值赋值给 formData */
watch(
() => props.propFormData,
(data) => {
if (!data) {
return
}
copyValueToTarget(formData, data)
// 将 SKU 的属性,整理成 PropertyAndValues 数组
propertyList.value = getPropertyList(data)
},
{
immediate: true
}
)
/** 表单校验 */
const emit = defineEmits(['update:activeName'])
const validate = async () => {
if (!formRef) return
try {
// 校验 sku
skuListRef.value.validateSku()
await unref(formRef).validate()
// 校验通过更新数据
Object.assign(props.propFormData, formData)
} catch (e) {
message.error('【库存价格】不完善,请填写相关信息')
emit('update:activeName', 'sku')
throw e // 目的截断之后的校验
}
}
defineExpose({ validate })
/** 分销类型 */
const changeSubCommissionType = () => {
// 默认为零,类型切换后也要重置为零
for (const item of formData.skus!) {
item.firstBrokeragePrice = 0
item.secondBrokeragePrice = 0
}
}
/** 选择规格 */
const onChangeSpec = () => {
// 重置商品属性列表
propertyList.value = []
// 重置sku列表
formData.skus = [
{
price: 0,
marketPrice: 0,
costPrice: 0,
barCode: '',
picUrl: '',
stock: 0,
weight: 0,
volume: 0,
firstBrokeragePrice: 0,
secondBrokeragePrice: 0
}
]
}
/** 调用 SkuList generateTableData 方法*/
const generateSkus = (propertyList: any[]) => {
skuListRef.value.generateTableData(propertyList)
}
</script>
@@ -0,0 +1,205 @@
<template>
<ContentWrap v-loading="formLoading">
<el-tabs v-model="activeName">
<el-tab-pane label="基础设置" name="info">
<InfoForm
ref="infoRef"
v-model:activeName="activeName"
:is-detail="isDetail"
:propFormData="formData"
/>
</el-tab-pane>
<el-tab-pane label="价格库存" name="sku">
<SkuForm
ref="skuRef"
v-model:activeName="activeName"
:is-detail="isDetail"
:propFormData="formData"
/>
</el-tab-pane>
<el-tab-pane label="物流设置" name="delivery">
<DeliveryForm
ref="deliveryRef"
v-model:activeName="activeName"
:is-detail="isDetail"
:propFormData="formData"
/>
</el-tab-pane>
<el-tab-pane label="商品详情" name="description">
<DescriptionForm
ref="descriptionRef"
v-model:activeName="activeName"
:is-detail="isDetail"
:propFormData="formData"
/>
</el-tab-pane>
<el-tab-pane label="其它设置" name="other">
<OtherForm
ref="otherRef"
v-model:activeName="activeName"
:is-detail="isDetail"
:propFormData="formData"
/>
</el-tab-pane>
</el-tabs>
<el-form>
<el-form-item style="float: right">
<el-button v-if="!isDetail" :loading="formLoading" type="primary" @click="submitForm">
保存
</el-button>
<el-button @click="close">返回</el-button>
</el-form-item>
</el-form>
</ContentWrap>
</template>
<script lang="ts" setup>
import { cloneDeep } from 'lodash-es'
import { useTagsViewStore } from '@/store/modules/tagsView'
import * as ProductSpuApi from '@/api/mall/product/spu'
import InfoForm from './InfoForm.vue'
import DescriptionForm from './DescriptionForm.vue'
import OtherForm from './OtherForm.vue'
import SkuForm from './SkuForm.vue'
import DeliveryForm from './DeliveryForm.vue'
import { convertToInteger, floatToFixed2, formatToFraction } from '@/utils'
defineOptions({ name: 'ProductPickupAdd' })
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { push, currentRoute } = useRouter() // 路由
const { params, name } = useRoute() // 查询参数
const { delView } = useTagsViewStore() // 视图操作
const formLoading = ref(false) // 表单的加载中:1)修改时的数据加载;2)提交的按钮禁用
const activeName = ref('info') // Tag 激活的窗口
const isDetail = ref(false) // 是否查看详情
const infoRef = ref() // 商品信息 Ref
const skuRef = ref() // 商品规格 Ref
const deliveryRef = ref() // 物流设置 Ref
const descriptionRef = ref() // 商品详情 Ref
const otherRef = ref() // 其他设置 Ref
// SPU 表单数据
const formData = ref<ProductSpuApi.Spu>({
name: '', // 商品名称
categoryId: undefined, // 商品分类
keyword: '', // 关键字
picUrl: '', // 商品封面图
sliderPicUrls: [], // 商品轮播图
introduction: '', // 商品简介
deliveryTypes: [], // 配送方式数组
deliveryTemplateId: undefined, // 运费模版
brandId: undefined, // 商品品牌
specType: false, // 商品规格
subCommissionType: false, // 分销类型
skus: [
{
price: 0, // 商品价格
marketPrice: 0, // 市场价
costPrice: 0, // 成本价
barCode: '', // 商品条码
picUrl: '', // 图片地址
stock: 0, // 库存
weight: 0, // 商品重量
volume: 0, // 商品体积
firstBrokeragePrice: 0, // 一级分销的佣金
secondBrokeragePrice: 0 // 二级分销的佣金
}
],
description: '', // 商品详情
sort: 0, // 商品排序
giveIntegral: 0, // 赠送积分
virtualSalesCount: 0 // 虚拟销量
})
/** 获得详情 */
const getDetail = async () => {
if ('ProductPickupDetail' === name) {
isDetail.value = true
}
const id = params.id as unknown as number
if (id) {
formLoading.value = true
try {
const res = (await ProductSpuApi.getSpu(id)) as ProductSpuApi.Spu
res.skus?.forEach((item) => {
if (isDetail.value) {
item.price = floatToFixed2(item.price)
item.marketPrice = floatToFixed2(item.marketPrice)
item.costPrice = floatToFixed2(item.costPrice)
item.firstBrokeragePrice = floatToFixed2(item.firstBrokeragePrice)
item.secondBrokeragePrice = floatToFixed2(item.secondBrokeragePrice)
} else {
// 回显价格分转元
item.price = formatToFraction(item.price)
item.marketPrice = formatToFraction(item.marketPrice)
item.costPrice = formatToFraction(item.costPrice)
item.firstBrokeragePrice = formatToFraction(item.firstBrokeragePrice)
item.secondBrokeragePrice = formatToFraction(item.secondBrokeragePrice)
}
})
formData.value = res
} finally {
formLoading.value = false
}
}
}
/** 提交按钮 */
const submitForm = async () => {
// 提交请求
formLoading.value = true
try {
// 校验各表单
await unref(infoRef)?.validate()
await unref(skuRef)?.validate()
await unref(deliveryRef)?.validate()
await unref(descriptionRef)?.validate()
await unref(otherRef)?.validate()
// 深拷贝一份, 这样最终 server 端不满足,不需要影响原始数据
const deepCopyFormData = cloneDeep(unref(formData.value)) as ProductSpuApi.Spu
deepCopyFormData.skus!.forEach((item) => {
// 给sku name赋值
item.name = deepCopyFormData.name
// sku相关价格元转分
item.price = convertToInteger(item.price)
item.marketPrice = convertToInteger(item.marketPrice)
item.costPrice = convertToInteger(item.costPrice)
item.firstBrokeragePrice = convertToInteger(item.firstBrokeragePrice)
item.secondBrokeragePrice = convertToInteger(item.secondBrokeragePrice)
})
// 处理轮播图列表
const newSliderPicUrls: any[] = []
deepCopyFormData.sliderPicUrls!.forEach((item: any) => {
// 如果是前端选的图
typeof item === 'object' ? newSliderPicUrls.push(item.url) : newSliderPicUrls.push(item)
})
deepCopyFormData.sliderPicUrls = newSliderPicUrls
// 校验都通过后提交表单
const data = deepCopyFormData as ProductSpuApi.Spu;
data.types = 1;
const id = params.id as unknown as number
if (!id) {
await ProductSpuApi.createSpu(data)
message.success(t('common.createSuccess'))
} else {
await ProductSpuApi.updateSpu(data)
message.success(t('common.updateSuccess'))
}
close()
} finally {
formLoading.value = false
}
}
/** 关闭按钮 */
const close = () => {
delView(unref(currentRoute))
push({ name: 'ProductPickup' })
}
/** 初始化 */
onMounted(async () => {
await getDetail()
})
</script>
@@ -0,0 +1,458 @@
<!-- 商品中心 - 商品列表 -->
<template>
<doc-alert title="【商品】商品 SPU 与 SKU" url="https://doc.iocoder.cn/mall/product-spu-sku/" />
<!-- 搜索工作栏 -->
<ContentWrap>
<el-form
ref="queryFormRef"
:inline="true"
:model="queryParams"
class="-mb-15px"
label-width="68px"
>
<el-form-item label="商品名称" prop="name">
<el-input
v-model="queryParams.name"
class="!w-240px"
clearable
placeholder="请输入商品名称"
@keyup.enter="handleQuery"
/>
</el-form-item>
<el-form-item label="商品分类" prop="categoryId">
<el-cascader
v-model="queryParams.categoryId"
:options="categoryList"
:props="defaultProps"
class="w-1/1"
clearable
filterable
placeholder="请选择商品分类"
/>
</el-form-item>
<el-form-item label="创建时间" prop="createTime">
<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-form-item>
<el-form-item>
<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-button
v-hasPermi="['product:spu:create']"
plain
type="primary"
@click="openForm(undefined)"
>
<Icon class="mr-5px" icon="ep:plus" />
新增
</el-button>
<el-button
v-hasPermi="['product:spu:export']"
:loading="exportLoading"
plain
type="success"
@click="handleExport"
>
<Icon class="mr-5px" icon="ep:download" />
导出
</el-button>
</el-form-item>
</el-form>
</ContentWrap>
<!-- 列表 -->
<ContentWrap>
<el-tabs v-model="queryParams.tabType" @tab-click="handleTabClick">
<el-tab-pane
v-for="item in tabsData"
:key="item.type"
:label="item.name + '(' + item.count + ')'"
:name="item.type"
/>
</el-tabs>
<el-table v-loading="loading" :data="list">
<el-table-column type="expand">
<template #default="{ row }">
<el-form class="spu-table-expand" label-position="left">
<el-row>
<el-col :span="24">
<el-row>
<el-col :span="8">
<el-form-item label="商品分类:">
<span>{{ formatCategoryName(row.categoryId) }}</span>
</el-form-item>
</el-col>
<el-col :span="8">
<el-form-item label="市场价:">
<span>{{ fenToYuan(row.marketPrice) }}</span>
</el-form-item>
</el-col>
<el-col :span="8">
<el-form-item label="成本价:">
<span>{{ fenToYuan(row.costPrice) }}</span>
</el-form-item>
</el-col>
</el-row>
</el-col>
</el-row>
<el-row>
<el-col :span="24">
<el-row>
<el-col :span="8">
<el-form-item label="浏览量:">
<span>{{ row.browseCount }}</span>
</el-form-item>
</el-col>
<el-col :span="8">
<el-form-item label="虚拟销量:">
<span>{{ row.virtualSalesCount }}</span>
</el-form-item>
</el-col>
</el-row>
</el-col>
</el-row>
</el-form>
</template>
</el-table-column>
<el-table-column label="商品编号" min-width="140" prop="id" />
<el-table-column label="商品信息" min-width="300">
<template #default="{ row }">
<div class="flex">
<el-image
fit="cover"
:src="row.picUrl"
class="flex-none w-50px h-50px"
@click="imagePreview(row.picUrl)"
/>
<div class="ml-4 overflow-hidden">
<el-tooltip effect="dark" :content="row.name" placement="top">
<div>
{{ row.name }}
</div>
</el-tooltip>
</div>
</div>
</template>
</el-table-column>
<el-table-column align="center" label="价格" min-width="160" prop="price">
<template #default="{ row }"> ¥ {{ fenToYuan(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 align="center" label="销售状态" min-width="80">
<template #default="{ row }">
<template v-if="row.status >= 0">
<el-switch
v-model="row.status"
:active-value="1"
:inactive-value="0"
active-text="上架"
inactive-text="下架"
inline-prompt
@change="handleStatusChange(row)"
/>
</template>
<template v-else>
<el-tag type="info">回收站</el-tag>
</template>
</template>
</el-table-column>
<el-table-column
:formatter="dateFormatter"
align="center"
label="创建时间"
prop="createTime"
width="180"
/>
<el-table-column align="center" fixed="right" label="操作" min-width="200">
<template #default="{ row }">
<el-button link type="primary" @click="openDetail(row.id)"> 详情 </el-button>
<el-button
v-hasPermi="['product:spu:update']"
link
type="primary"
@click="openForm(row.id)"
>
修改
</el-button>
<template v-if="queryParams.tabType === 4">
<el-button
v-hasPermi="['product:spu:delete']"
link
type="danger"
@click="handleDelete(row.id)"
>
删除
</el-button>
<el-button
v-hasPermi="['product:spu:update']"
link
type="primary"
@click="handleStatus02Change(row, ProductSpuStatusEnum.DISABLE.status)"
>
恢复
</el-button>
</template>
<template v-else>
<el-button
v-hasPermi="['product:spu:update']"
link
type="danger"
@click="handleStatus02Change(row, ProductSpuStatusEnum.RECYCLE.status)"
>
回收
</el-button>
</template>
</template>
</el-table-column>
</el-table>
<!-- 分页 -->
<Pagination
v-model:limit="queryParams.pageSize"
v-model:page="queryParams.pageNo"
:total="total"
@pagination="getList"
/>
</ContentWrap>
</template>
<script lang="ts" setup>
import { TabsPaneContext } from 'element-plus'
import { createImageViewer } from '@/components/ImageViewer'
import { dateFormatter } from '@/utils/formatTime'
import { defaultProps, handleTree, treeToString } from '@/utils/tree'
import { ProductSpuStatusEnum } from '@/utils/constants'
import { fenToYuan } from '@/utils'
import download from '@/utils/download'
import * as ProductSpuApi from '@/api/mall/product/spu'
import * as ProductCategoryApi from '@/api/mall/product/category'
defineOptions({ name: 'ProductPickup' })
const message = useMessage() // 消息弹窗
const route = useRoute() // 路由
const { t } = useI18n() // 国际化
const { push } = useRouter() // 路由跳转
const loading = ref(false) // 列表的加载中
const exportLoading = ref(false) // 导出的加载中
const total = ref(0) // 列表的总页数
const list = ref<ProductSpuApi.Spu[]>([]) // 列表的数据
// tabs 数据
const tabsData = ref([
{
name: '出售中',
type: 0,
count: 0
},
{
name: '仓库中',
type: 1,
count: 0
},
{
name: '已售罄',
type: 2,
count: 0
},
{
name: '警戒库存',
type: 3,
count: 0
},
{
name: '回收站',
type: 4,
count: 0
}
])
const queryParams = ref({
pageNo: 1,
pageSize: 10,
tabType: 0,
name: '',
categoryId: undefined,
createTime: undefined,
types:1
}) // 查询参数
const queryFormRef = ref() // 搜索的表单Ref
/** 查询列表 */
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
}
}
/** 切换 Tab */
const handleTabClick = (tab: TabsPaneContext) => {
queryParams.value.tabType = tab.paneName as number
getList()
}
/** 获得每个 Tab 的数量 */
const getTabsCount = async () => {
const res = await ProductSpuApi.getTabsCount()
for (let objName in res) {
tabsData.value[Number(objName)].count = res[objName]
}
}
/** 添加到仓库 / 回收站的状态 */
const handleStatus02Change = async (row: any, newStatus: number) => {
try {
// 二次确认
const text = newStatus === ProductSpuStatusEnum.RECYCLE.status ? '加入到回收站' : '恢复到仓库'
await message.confirm(`确认要"${row.name}"${text}吗?`)
// 发起修改
await ProductSpuApi.updateStatus({ id: row.id, status: newStatus })
message.success(text + '成功')
// 刷新 tabs 数据
await getTabsCount()
// 刷新列表
await getList()
} catch {}
}
/** 更新上架/下架状态 */
const handleStatusChange = async (row: any) => {
try {
// 二次确认
const text = row.status ? '上架' : '下架'
await message.confirm(`确认要${text}"${row.name}"吗?`)
// 发起修改
await ProductSpuApi.updateStatus({ id: row.id, status: row.status })
message.success(text + '成功')
// 刷新 tabs 数据
await getTabsCount()
// 刷新列表
await getList()
} catch {
// 异常时,需要重置回之前的值
row.status =
row.status === ProductSpuStatusEnum.DISABLE.status
? ProductSpuStatusEnum.ENABLE.status
: ProductSpuStatusEnum.DISABLE.status
}
}
/** 删除按钮操作 */
const handleDelete = async (id: number) => {
try {
// 删除的二次确认
await message.delConfirm()
// 发起删除
await ProductSpuApi.deleteSpu(id)
message.success(t('common.delSuccess'))
// 刷新tabs数据
await getTabsCount()
// 刷新列表
await getList()
} catch {}
}
/** 商品图预览 */
const imagePreview = (imgUrl: string) => {
createImageViewer({
urlList: [imgUrl]
})
}
/** 搜索按钮操作 */
const handleQuery = () => {
getList()
}
/** 重置按钮操作 */
const resetQuery = () => {
queryFormRef.value.resetFields()
handleQuery()
}
/** 新增或修改 */
const openForm = (id?: number) => {
// 修改
if (typeof id === 'number') {
push({ name: 'ProductPickupEdit', params: { id } })
return
}
// 新增
push({ name: 'ProductPickupAdd' });
}
/** 查看商品详情 */
const openDetail = (id: number) => {
push({ name: 'ProductPickupDetail', params: { id } })
}
/** 导出按钮操作 */
const handleExport = async () => {
try {
// 导出的二次确认
await message.exportConfirm()
// 发起导出
exportLoading.value = true
const data = await ProductSpuApi.exportSpu(queryParams.value)
download.excel(data, '商品列表.xls')
} catch {
} finally {
exportLoading.value = false
}
}
/** 获取分类的节点的完整结构 */
const categoryList = ref() // 分类树
const formatCategoryName = (categoryId: number) => {
return treeToString(categoryList.value, categoryId)
}
/** 激活时 */
onActivated(() => {
getList()
})
/** 初始化 **/
onMounted(async () => {
// 解析路由的 categoryId
if (route.query.categoryId) {
queryParams.value.categoryId = route.query.categoryId
}
// 获得商品信息
await getTabsCount()
await getList()
// 获得分类树
const data = await ProductCategoryApi.getCategoryList({})
categoryList.value = handleTree(data, 'id', 'parentId')
})
</script>
<style lang="scss" scoped>
.spu-table-expand {
padding-left: 42px;
:deep(.el-form-item__label) {
width: 82px;
font-weight: bold;
color: #99a9bf;
}
}
</style>
+2 -1
View File
@@ -174,7 +174,8 @@ const submitForm = async () => {
// 如果是前端选的图
typeof item === 'object' ? newSliderPicUrls.push(item.url) : newSliderPicUrls.push(item)
})
deepCopyFormData.sliderPicUrls = newSliderPicUrls
deepCopyFormData.sliderPicUrls = newSliderPicUrls;
deepCopyFormData.types = 0;
// 校验都通过后提交表单
const data = deepCopyFormData as ProductSpuApi.Spu
const id = params.id as unknown as number
+2 -1
View File
@@ -287,7 +287,8 @@ const queryParams = ref({
tabType: 0,
name: '',
categoryId: undefined,
createTime: undefined
createTime: undefined,
types:0
}) // 查询参数
const queryFormRef = ref() // 搜索的表单Ref