feat(GoodsStock.vue): 商品库存管理升级vue3

This commit is contained in:
郝先瑞
2022-01-10 23:48:19 +08:00
parent 932c78f988
commit d591ddde7c
8 changed files with 578 additions and 457 deletions

View File

@@ -17,6 +17,7 @@
"path-to-regexp": "^6.2.0", "path-to-regexp": "^6.2.0",
"pinia": "^2.0.9", "pinia": "^2.0.9",
"screenfull": "^6.0.0", "screenfull": "^6.0.0",
"sortablejs": "^1.14.0",
"vue": "^3.2.16", "vue": "^3.2.16",
"vue-router": "^4.0.12" "vue-router": "^4.0.12"
}, },

View File

@@ -58,7 +58,6 @@ import {listAttributes, saveAttributeBatch} from "@/api/pms/attribute";
import {computed, reactive, toRefs, watch} from "vue"; import {computed, reactive, toRefs, watch} from "vue";
import {Plus, Check, Delete} from '@element-plus/icons' import {Plus, Check, Delete} from '@element-plus/icons'
import {ElMessage} from "element-plus"; import {ElMessage} from "element-plus";
import {listRoleMenuIds} from "@api/system/role";
import SvgIcon from '@/components/SvgIcon/index.vue'; import SvgIcon from '@/components/SvgIcon/index.vue';
const props = defineProps({ const props = defineProps({

View File

@@ -1,29 +1,34 @@
<!--
<template> <template>
<div class="components-container"> <div class="components-container">
<div class="components-container__main"> <div class="components-container__main">
<el-card class="box-card"> <el-card class="box-card">
<div slot="header"> <template #header>
<span>商品属性</span> <span>商品属性</span>
<el-button style="float: right;" type="primary" size="mini" @click="handleAttributeAdd"> <el-button
style="float: right;"
type="success"
:icon="Plus"
size="mini"
@click="handleAdd"
>
添加属性 添加属性
</el-button> </el-button>
</div> </template>
<el-form <el-form
ref="attributeForm" ref="dataForm"
:model="value" :model="modelValue"
:rules="rules" :rules="rules"
size="mini" size="mini"
:inline="true" :inline="true"
> >
<el-table <el-table
:data="value.attrList" :data="modelValue.attrList"
size="mini" size="mini"
highlight-current-row highlight-current-row
border border
> >
<el-table-column property="name" label="属性名称"> <el-table-column property="name" label="属性名称">
<template slot-scope="scope"> <template #default="scope">
<el-form-item <el-form-item
:prop="'attrList[' + scope.$index + '].name'" :prop="'attrList[' + scope.$index + '].name'"
:rules="rules.attribute.name" :rules="rules.attribute.name"
@@ -34,7 +39,7 @@
</el-table-column> </el-table-column>
<el-table-column property="value" label="属性值"> <el-table-column property="value" label="属性值">
<template slot-scope="scope"> <template #default="scope">
<el-form-item <el-form-item
:prop="'attrList[' + scope.$index + '].value'" :prop="'attrList[' + scope.$index + '].value'"
:rules="rules.attribute.value" :rules="rules.attribute.value"
@@ -45,9 +50,15 @@
</el-table-column> </el-table-column>
<el-table-column label="操作" width="150"> <el-table-column label="操作" width="150">
<template slot-scope="scope"> <template #default="scope">
<el-form-item> <el-form-item>
<el-button type="danger" icon="el-icon-minus" circle @click="handleAttributeRemove(scope.$index)"/> <el-button
v-if="scope.$index>0"
type="danger"
icon="Minus"
circle
@click="handleRemove(scope.$index)"
/>
</el-form-item> </el-form-item>
</template> </template>
</el-table-column> </el-table-column>
@@ -63,53 +74,77 @@
</div> </div>
</template> </template>
<script> <script setup lang="ts">
import {listAttribute} from "@/api/pms/attribute"; import {listAttributes} from "@/api/pms/attribute";
import {computed, nextTick, reactive, ref, toRefs, unref, watch} from "vue";
import {ElForm} from "element-plus";
import {Minus, Plus} from '@element-plus/icons'
export default { const emit = defineEmits(['prev', 'next'])
name: "GoodsAttribute", const dataForm = ref(ElForm)
props: {
value: Object const props = defineProps({
}, modelValue: {
watch:{ type: Object,
// 监听选择的商品分类关联商品属性 default: {}
'value.categoryId':{ }
handler(newVal,oldVal){
listAttribute({categoryId: newVal, type: 2}).then(res => {
this.value.attrList = res.data
}) })
const categoryId = computed(() => props.modelValue.categoryId);
watch(categoryId, (newVal, oldVal) => {
if (newVal) {
// type=2 商品普通属性(非销售属性)
listAttributes({categoryId: newVal, type: 2}).then(response => {
const attrList = response.data
if (attrList && attrList.length > 0) {
props.modelValue.attrList = attrList
} else {
props.modelValue.attrList = [{}]
} }
})
} else {
props.modelValue.attrList = [{}]
} }
}, },
data() { {
return { immediate: true,
deep: true
}
)
const state = reactive({
rules: { rules: {
attribute: { attribute: {
name: [{required: true, message: '请填写属性名称', trigger: 'blur'}], name: [{required: true, message: '请填写属性名称', trigger: 'blur'}],
value: [{required: true, message: '请填写属性值', trigger: 'blur'}] value: [{required: true, message: '请填写属性值', trigger: 'blur'}]
} }
},
} }
}, })
methods: {
handleAttributeAdd: function () { const {rules} = toRefs(state)
this.value.attrList.push({})
}, function handleAdd() {
handleAttributeRemove: function (index) { props.modelValue.attrList.push({})
this.value.attrList.splice(index, 1) }
},
handlePrev: function () { function handleRemove(index:number) {
this.$emit('prev') props.modelValue.attrList.splice(index, 1)
}, }
handleNext: function () {
this.$refs["attributeForm"].validate((valid) => { function handlePrev() {
emit('prev')
}
function handleNext() {
const form = unref(dataForm)
form.validate((valid: any) => {
if (valid) { if (valid) {
this.$emit('next') emit('next')
} }
}) })
} }
}
}
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
@@ -125,8 +160,8 @@ export default {
right: 20px; right: 20px;
} }
} }
.el-form-item&#45;&#45;mini.el-form-item{
.el-form-item--mini.el-form-item {
margin-top: 18px; margin-top: 18px;
} }
</style> </style>
-->

View File

@@ -4,7 +4,7 @@
<el-cascader-panel <el-cascader-panel
ref="categoryRef" ref="categoryRef"
:options="categoryOptions" :options="categoryOptions"
v-model="categoryId" v-model="modelValue.categoryId"
:props="{emitPath:false}" :props="{emitPath:false}"
@change="handleCategoryChange" @change="handleCategoryChange"
@@ -40,17 +40,15 @@ const props = defineProps({
const state = reactive({ const state = reactive({
categoryOptions: [], categoryOptions: [],
pathLabels: [], pathLabels: []
categoryId: undefined
}) })
const {categoryOptions, pathLabels, categoryId} = toRefs(state) const {categoryOptions, pathLabels} = toRefs(state)
function loadData() { function loadData() {
listCascadeCategories({}).then(response => { listCascadeCategories({}).then(response => {
state.categoryOptions = response.data state.categoryOptions = response.data
if (props.modelValue.id) { if (props.modelValue.id) {
state.categoryId = props.modelValue.categoryId
nextTick(() => { nextTick(() => {
handleCategoryChange() handleCategoryChange()
}) })
@@ -66,7 +64,8 @@ function handleCategoryChange() {
} }
function handleNext() { function handleNext() {
if (!state.categoryId) { console.log('商品属性',props.modelValue.categoryId)
if (!props.modelValue.categoryId) {
ElMessage.warning('请选择商品分类') ElMessage.warning('请选择商品分类')
return false return false
} }

View File

@@ -1,21 +1,22 @@
<!--
<template> <template>
<div class="components-container"> <div class="components-container">
<div class="components-container__main"> <div class="components-container__main">
<el-card class="box-card"> <el-card class="box-card">
<div slot="header"> <template #header>
<span>商品规格</span> <span>商品规格</span>
<el-button style="float: right;" type="primary" size="mini" @click="handleSpecAdd"> <el-button style="float: right;" type="primary" size="mini" @click="handleSpecAdd">
添加规格项 添加规格项
</el-button> </el-button>
</div> </template>
<el-form <el-form
size="mini" ref="specFormRef"
ref="specForm"
:model="specForm" :model="specForm"
:inline="true"> :inline="true"
size="mini"
>
<el-table <el-table
ref="specTable" ref="specTableRef"
:data="specForm.specList" :data="specForm.specList"
row-key="id" row-key="id"
size="mini" size="mini"
@@ -26,16 +27,16 @@
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="规格名" width="200"> <el-table-column label="规格名" width="200">
<template slot-scope="scope"> <template #default="scope">
<el-form-item <el-form-item
:prop="'specList[' + scope.$index + '].name'" :prop="'specList[' + scope.$index + '].name'"
:rules="rules.specification.name" :rules="rules.spec.name"
> >
<el-input <el-input
type="text" type="text"
v-model="scope.row.name" v-model="scope.row.name"
size="mini" size="mini"
@input="changeSpec()" @input="handleSpecChange()"
/> />
</el-form-item> </el-form-item>
</template> </template>
@@ -69,7 +70,7 @@
</el-table-column> </el-table-column>
<el-table-column width="60" label="操作"> <el-table-column width="60" label="操作">
<template slot-scope="scope"> <template #default="scope">
<el-button <el-button
type="danger" type="danger"
icon="el-icon-delete" icon="el-icon-delete"
@@ -82,52 +83,60 @@
</el-table> </el-table>
</el-form> </el-form>
</el-card> </el-card>
<el-card class="box-card"> <el-card class="box-card">
<div slot="header"> <template #header>
<span>商品库存</span> <span>商品库存</span>
</div> </template>
<el-form <el-form
ref="skuFormRef"
:model="skuForm" :model="skuForm"
size="mini" size="mini"
ref="skuForm"
:inline="true" :inline="true"
> >
<el-table <el-table
:data="skuForm.skuList" :data="skuForm.skuList"
:span-method="handleCellMerge" :span-method="handleCellMerge"
highlight-current-row
size="mini" size="mini"
fit highlight-current-row border fit
border
> >
<el-table-column <el-table-column
v-for="(title,index) in specTitleList" v-for="(title,index) in specTitles"
align="center" align="center"
:prop="'specValue'+(index+1)" :prop="'specValue'+(index+1)"
:label="title"> :label="title">
</el-table-column> </el-table-column>
<el-table-column <el-table-column
label="商品编码" label="商品编码"
align="center" align="center"
> >
<template slot-scope="scope"> <template #default="scope">
<el-form-item :prop="'skuList['+scope.$index+'].sn'" :rules="rules.sku.sn"> <el-form-item :prop="'skuList['+scope.$index+'].sn'" :rules="rules.sku.sn">
<el-input v-model="scope.row.sn"/> <el-input v-model="scope.row.sn"/>
</el-form-item> </el-form-item>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="价格" align="center"> <el-table-column label="价格" align="center">
<template slot-scope="scope"> <template #default="scope">
<el-form-item :prop="'skuList['+scope.$index+'].price'" :rules="rules.sku.price"> <el-form-item :prop="'skuList['+scope.$index+'].price'" :rules="rules.sku.price">
<el-input v-model="scope.row.price"/> <el-input v-model="scope.row.price"/>
</el-form-item> </el-form-item>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="库存" align="center"> <el-table-column label="库存" align="center">
<template slot-scope="scope"> <template #default="scope">
<el-form-item :prop="'skuList['+scope.$index+'].stock'" :rules="rules.sku.stock"> <el-form-item :prop="'skuList['+scope.$index+'].stock'" :rules="rules.sku.stock">
<el-input v-model="scope.row.stock"/> <el-input v-model="scope.row.stock"/>
</el-form-item> </el-form-item>
</template> </template>
</el-table-column> </el-table-column>
</el-table> </el-table>
</el-form> </el-form>
</el-card> </el-card>
@@ -139,49 +148,44 @@
</div> </div>
</template> </template>
<script> <script setup lang="ts">
import {listAttribute} from "@/api/pms/attribute"; import {listAttributes} from "@/api/pms/attribute";
import MiniCardUpload from '@/components/Upload/MiniCardUpload' import MiniCardUpload from '@/components/Upload/MiniCardUpload.vue'
import Sortable from "sortablejs"; import Sortable from 'sortablejs'
import {addGoods, updateGoods} from "@/api/pms/goods"; import {addGoods, updateGoods} from "@/api/pms/goods";
import {computed, getCurrentInstance, nextTick, onMounted, reactive, ref, toRefs, unref, watch} from "vue";
import {ElMessage, ElTable, ElForm} from "element-plus"
import {useRouter} from "vue-router";
const emit = defineEmits(['prev', 'next'])
export default { const proxy = getCurrentInstance() as any
name: "GoodsStock", const router = useRouter()
components: {MiniCardUpload},
props: {
value: Object
},
watch: {
// 监听选择的商品分类关联商品属性项
'value.categoryId': {
handler(newVal, oldVal) {
listAttribute({categoryId: newVal, type: 1}).then(res => {
res.data.forEach(item => {
console.log('规格项目', item)
this.specForm.specList.push({
name: item.name,
values: []
})
this.loadData()
}) const specTableRef = ref(ElTable)
}) const specFormRef = ref(ElForm)
const skuFormRef = ref(ElForm)
const props = defineProps({
modelValue: {
type: Object,
default: {}
} }
} })
},
data() { const categoryId = computed(() => props.modelValue.categoryId);
return {
// 包装一层用于表单验证 const state = reactive({
specForm: { specForm: {
specList: [], specList: [] as Array<any>,
}, },
skuForm: { skuForm: {
skuList: [] skuList: []
}, },
specTitleList: [], // 规格项表格标题 // 规格项表格标题
specTitles: [],
rules: { rules: {
specification: { spec: {
name: [{required: true, message: '请输入规格名称', trigger: 'blur'}], name: [{required: true, message: '请输入规格名称', trigger: 'blur'}],
value: [{required: true, message: '请输入规格值', trigger: 'blur'}] value: [{required: true, message: '请输入规格值', trigger: 'blur'}]
}, },
@@ -194,137 +198,130 @@ export default {
colors: ['', 'success', 'warning', 'danger'], colors: ['', 'success', 'warning', 'danger'],
tagInputs: [{value: undefined, visible: false}], // 规格值标签临时值和显隐控制 tagInputs: [{value: undefined, visible: false}], // 规格值标签临时值和显隐控制
loading: undefined loading: undefined
} })
},
created() {
if (this.value.id) {
this.loadData()
}
const {specForm, skuForm, specTitles, rules, colors, tagInputs, loading} = toRefs(state)
watch(categoryId, (newVal, oldVal) => {
if (newVal) {
// type=1 商品规格(销售属性)
listAttributes({categoryId: newVal, type: 1}).then(response => {
const specList = response.data
if (specList && specList.length > 0) {
specList.forEach((item: any) => {
state.specForm.specList.push({
name: item.name,
values: []
})
})
}
})
}
}, },
methods: { {
async loadData() { immediate: true,
this.value.specList.forEach(spec => { deep: true
const index = this.specForm.specList.findIndex(item => item.name == spec.name) }
if (index > -1) { )
this.specForm.specList[index].values.push({id: spec.id, value: spec.value, picUrl: spec.picUrl})
function loadData() {
const goodsId = props.modelValue.id
// 编辑数据加载
if (goodsId) {
props.modelValue.specList.forEach((specItem: any) => {
const specIndex = state.specForm.specList.findIndex(item => item.name == specItem.name)
if (specIndex > -1) {
state.specForm.specList[specIndex].values.push({
id: specItem.id,
value: specItem.value,
picUrl: specItem.picUrl
})
} else { } else {
this.specForm.specList.push({ state.specForm.specList.push({
name: spec.name, name: specItem.name,
values: [{id: spec.id, value: spec.value, picUrl: spec.picUrl}] values: [{id: specItem.id, value: specItem.value, picUrl: specItem.picUrl}]
}) })
} }
}) })
// 每个规格项追加一个添加规格值按钮 // 每个规格项追加一个添加规格值按钮
for (let i = 0; i < this.specForm.specList.length; i++) { for (let i = 0; i < state.specForm.specList.length; i++) {
this.tagInputs.push({'value': undefined, 'visible': false}) state.tagInputs.push({'value': undefined, 'visible': false})
} }
// SKU规格ID拼接字符串处理 // SKU规格ID拼接字符串处理
this.value.skuList.forEach(sku => { props.modelValue.skuList.forEach((sku: any) => {
sku.specIdArr = sku.specIds.split('_') sku.specIdArr = sku.specIds.split('_')
}) })
this.generateSku() generateSkuList()
this.changeSpec()
this.sortSpec() handleSpecChange()
this.$nextTick(() => {
this.setSort() handleSpecReorder()
nextTick(() => {
registerSpecDragSortEvent()
}) })
},
handleSpecAdd: function () {
if (this.specForm.specList.length >= 3) {
this.$message.warning('最多支持3组规格')
return
} }
this.specForm.specList.push({}) }
this.tagInputs.push({'value': undefined, 'visible': false})
this.sortSpec() /**
}, * 生成SKU列表的title
handleSpecRemove: function (index) { */
this.specForm.specList.splice(index, 1) function handleSpecChange() {
this.tagInputs.splice(index, 1) const specList = JSON.parse(JSON.stringify(state.specForm.specList))
this.generateSku() state.specTitles = specList.map((item: any) => item.name)
this.sortSpec() }
this.changeSpec()
}, /**
sortSpec: function () { * 规格列表重排序
this.specForm.specList.forEach((item, index) => { */
function handleSpecReorder() {
state.specForm.specList.forEach((item, index) => {
item.index = index item.index = index
}) })
}, }
handleSpecValueRemove: function (rowIndex, specValueId) {
const specList = JSON.parse(JSON.stringify(this.specForm.specList))
const removeIndex = specList[rowIndex].values.map(item => item.id).indexOf(specValueId)
console.log('removeIndex', removeIndex)
specList[rowIndex].values.splice(removeIndex, 1) /**
this.specForm.specList = specList * 注册拖拽排序事件
this.changeSpec() */
this.generateSku() function registerSpecDragSortEvent() {
}, const el = specTableRef.value.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
handleSpecValueInput: function (rowIndex) {
const currSpecValue = this.tagInputs[rowIndex].value
const specValues = this.specForm.specList[rowIndex].values
if (specValues && specValues.length > 0 && specValues.map(item => item.value).includes(currSpecValue)) {
this.$message.warning("规格值重复,请重新输入")
return false
}
if (currSpecValue) {
if (specValues && specValues.length > 0) {
// 临时规格值ID tid_1_1
let maxSpecValueIndex = specValues.filter(item => item.id.includes('tid_')).map(item => item.id.split('_')[2]).reduce((acc, curr) => {
return acc > curr ? acc : curr
}, 0)
console.log('maxSpecValueIndex', maxSpecValueIndex)
this.specForm.specList[rowIndex].values[specValues.length] = {
'value': currSpecValue,
'id': 'tid_' + (rowIndex + 1) + '_' + ++maxSpecValueIndex
}
} else {
this.specForm.specList[rowIndex].values = [{'value': currSpecValue, 'id': 'tid_' + (rowIndex + 1) + '_1'}]
}
}
this.tagInputs[rowIndex].value = undefined
this.tagInputs[rowIndex].visible = false
// 生成SKU列表
this.generateSku()
},
handleSpecValueAdd: function (rowIndex) {
this.tagInputs[rowIndex].visible = true
},
setSort() {
const el = this.$refs.specTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
Sortable.create(el, { Sortable.create(el, {
ghostClass: 'sortable-ghost', // Class name for the drop placeholder, ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
setData: function (dataTransfer) { setData: function (dataTransfer: any) {
dataTransfer.setData('Text', '') dataTransfer.setData('Text', '')
}, },
onEnd: evt => { onEnd: (evt: any) => {
// oldIndex 拖拽行当前所在索引 // oldIndex 拖拽行当前所在索引
// newIndex 拖拽行目标索引 // newIndex 拖拽行目标索引
const targetRow = this.specForm.specList.splice(evt.oldIndex, 1)[0] // 返回被删除的行 const targetRow = state.specForm.specList.splice(evt.oldIndex, 1)[0] // 返回被删除的行
this.specForm.specList.splice(evt.newIndex, 0, targetRow) // 拼接 state.specForm.specList.splice(evt.newIndex, 0, targetRow) // 拼接
this.generateSku() // 重新生成sku generateSkuList() // 重新生成sku
this.sortSpec() handleSpecChange()
this.changeSpec() handleSpecReorder()
} }
}) })
}, }
generateSku: function () {
// [
// { 'id':1,'name':'颜色','values':[{id:1,value:'白色'},{id:2,value:'黑色'},{id:3,value:'蓝色'}] },
// { 'id':2,'name':'版本','values':[{id:1,value:'6+128G'},{id:2,value:'8+128G'},{id:3,value:'8G+256G'}] }
// ]
const specList = JSON.parse(JSON.stringify(this.specForm.specList.filter(item => item.values.length > 0))) // 深拷贝取有属性的规格项否则笛卡尔积运算得到的SKU列表值为空
const skuList = specList.reduce((acc, curr) => { /**
let result = [] * 根据商品规格笛卡尔积生成SKU列表
acc.forEach(item => { *
* 规格列表:
* [
* { 'id':1,'name':'颜色','values':[{id:1,value:'白色'},{id:2,value:'黑色'},{id:3,value:'蓝色'}] },
* { 'id':2,'name':'版本','values':[{id:1,value:'6+128G'},{id:2,value:'8+128G'},{id:3,value:'8G+256G'}] }
* ]
*/
function generateSkuList() {
const specList = JSON.parse(JSON.stringify(state.specForm.specList.filter(item => item.values.length > 0))) // 深拷贝取有属性的规格项否则笛卡尔积运算得到的SKU列表值为空
const skuList = specList.reduce((acc: any, curr: any) => {
let result = [] as any
acc.forEach((item: any) => {
// curr => { 'id':1,'name':'颜色','values':[{id:1,value:'白色'},{id:2,value:'黑色'},{id:3,value:'蓝色'}] } // curr => { 'id':1,'name':'颜色','values':[{id:1,value:'白色'},{id:2,value:'黑色'},{id:3,value:'蓝色'}] }
curr.values.forEach(v => { // v=>{id:1,value:'白色'} curr.values.forEach((v: any) => { // v=>{id:1,value:'白色'}
let temp = Object.assign({}, item) let temp = Object.assign({}, item)
temp.specValues += v.value + '_' // 规格值拼接 temp.specValues += v.value + '_' // 规格值拼接
temp.specIds += v.id + '|' // 规格ID拼接 temp.specIds += v.id + '|' // 规格ID拼接
@@ -334,11 +331,16 @@ export default {
return result return result
}, [{specValues: '', specIds: ''}]) }, [{specValues: '', specIds: ''}])
skuList.forEach(item => { skuList.forEach((item: any) => {
item.specIds = item.specIds.substring(0, item.specIds.length - 1) item.specIds = item.specIds.substring(0, item.specIds.length - 1)
item.name = item.specValues.substring(0, item.specIds.length - 1).replaceAll('_', ' ') item.name = item.specValues.substring(0, item.specIds.length - 1).replaceAll('_', ' ')
const specIdArr = item.specIds.split('|') const specIdArr = item.specIds.split('|')
const skus = this.value.skuList.filter(sku => sku.specIdArr.equals(specIdArr)) // 数据库的SKU列表 const skus = props.modelValue.skuList.filter((sku: any) =>
sku.specIdArr.length === specIdArr.length &&
sku.specIdArr.every((a: number) => specIdArr.some((b: number) => a === b)) &&
specIdArr.every((x: number) => sku.specIdArr.some((y: number) => x === y))
) // 数据库的SKU列表
if (skus && skus.length > 0) { if (skus && skus.length > 0) {
const sku = skus[0] const sku = skus[0]
item.id = sku.id item.id = sku.id
@@ -347,35 +349,114 @@ export default {
item.stock = sku.stock item.stock = sku.stock
} }
const specValueArr = item.specValues.substring(0, item.specValues.length - 1).split('_') // ['黑','6+128G','官方标配'] const specValueArr = item.specValues.substring(0, item.specValues.length - 1).split('_') // ['黑','6+128G','官方标配']
specValueArr.forEach((v, i) => { specValueArr.forEach((v: any, i: any) => {
const key = 'specValue' + (i + 1) const key = 'specValue' + (i + 1)
item[key] = v item[key] = v
if (i == 0 && this.specForm.specList.length > 0) { if (i == 0 && state.specForm.specList.length > 0) {
const valueIndex = this.specForm.specList[0].values.findIndex(specValue => specValue.value == v) const valueIndex = state.specForm.specList[0].values.findIndex((specValue: any) => specValue.value == v)
if (valueIndex > -1) { if (valueIndex > -1) {
item.picUrl = this.specForm.specList[0].values[valueIndex].picUrl item.picUrl = state.specForm.specList[0].values[valueIndex].picUrl
} }
} }
}) })
}) })
this.skuForm.skuList = JSON.parse(JSON.stringify(skuList)) state.skuForm.skuList = JSON.parse(JSON.stringify(skuList))
}, }
changeSpec: function () {
const specList = JSON.parse(JSON.stringify(this.specForm.specList))
this.specTitleList = specList.map(item => item.name)
},
/** /**
* 合并规格值单元 * 添加规
*/ */
handleCellMerge({row, column, rowIndex, columnIndex}) { function handleSpecAdd() {
if (state.specForm.specList.length >= 3) {
ElMessage.warning('最多支持3组规格')
return
}
state.specForm.specList.push({})
state.tagInputs.push({'value': undefined, 'visible': false})
handleSpecReorder()
}
/**
* 删除规格
* @param index
*/
function handleSpecRemove(index: number) {
state.specForm.specList.splice(index, 1)
state.tagInputs.splice(index, 1)
generateSkuList()
handleSpecReorder()
handleSpecChange()
}
/**
* 添加规格值
*
* @param specIndex
*/
function handleSpecValueAdd(specIndex: number) {
state.tagInputs[specIndex].visible = true
}
/**
* 删除规格值
*
* @param rowIndex
* @param specValueId
*/
function handleSpecValueRemove(rowIndex: number, specValueId: number) {
const specList = JSON.parse(JSON.stringify(state.specForm.specList))
const removeIndex = specList[rowIndex].values.map((item: any) => item.id).indexOf(specValueId)
specList[rowIndex].values.splice(removeIndex, 1)
state.specForm.specList = specList
handleSpecChange()
handleSpecReorder()
}
/**
* 规格值输入
*/
function handleSpecValueInput(rowIndex: number) {
const currSpecValue = state.tagInputs[rowIndex].value
const specValues = state.specForm.specList[rowIndex].values
if (specValues && specValues.length > 0 && specValues.map((item: any) => item.value).includes(currSpecValue)) {
ElMessage.warning("规格值重复,请重新输入")
return false
}
if (currSpecValue) {
if (specValues && specValues.length > 0) {
// 临时规格值ID tid_1_1
let maxSpecValueIndex = specValues.filter((item: any) => item.id.includes('tid_')).map((item: any) => item.id.split('_')[2]).reduce((acc: any, curr: any) => {
return acc > curr ? acc : curr
}, 0)
console.log('maxSpecValueIndex', maxSpecValueIndex)
state.specForm.specList[rowIndex].values[specValues.length] = {
'value': currSpecValue,
'id': 'tid_' + (rowIndex + 1) + '_' + ++maxSpecValueIndex
}
} else {
state.specForm.specList[rowIndex].values = [{'value': currSpecValue, 'id': 'tid_' + (rowIndex + 1) + '_1'}]
}
}
state.tagInputs[rowIndex].value = undefined
state.tagInputs[rowIndex].visible = false
generateSkuList()
}
/**
* 合并规格单元格
*
* @param cellObj 单元格对象
*/
function handleCellMerge(cellObj: any) {
const {rowIndex, columnIndex} = cellObj
let mergeRows = [1, 1, 1] // 分别对应规格1、规格2、规格3列合并的行数 let mergeRows = [1, 1, 1] // 分别对应规格1、规格2、规格3列合并的行数
const specLen = this.specForm.specList.filter(item => item.values && item.values.length > 0).length const specLen = state.specForm.specList.filter(item => item.values && item.values.length > 0).length
if (specLen == 2) { if (specLen == 2) {
const values_len_2 = this.specForm.specList[1].values ? this.specForm.specList[1].values.length : 1 // 第2个规格项的规格值的数量 const values_len_2 = state.specForm.specList[1].values ? state.specForm.specList[1].values.length : 1 // 第2个规格项的规格值的数量
mergeRows = [values_len_2, 1, 1] mergeRows = [values_len_2, 1, 1]
} else if (specLen == 3) { } else if (specLen == 3) {
const values_len_2 = this.specForm.specList[1].values ? this.specForm.specList[1].values.length : 1 // 第2个规格项的规格值的数量 const values_len_2 = state.specForm.specList[1].values ? state.specForm.specList[1].values.length : 1 // 第2个规格项的规格值的数量
const values_len_3 = this.specForm.specList[2].values ? this.specForm.specList[2].values.length : 1 // 第3个规格项的规格值的数量 const values_len_3 = state.specForm.specList[2].values ? state.specForm.specList[2].values.length : 1 // 第3个规格项的规格值的数量
mergeRows = [values_len_2 * values_len_3, values_len_3, 1] mergeRows = [values_len_2 * values_len_3, values_len_3, 1]
} }
if (columnIndex == 0) { if (columnIndex == 0) {
@@ -392,90 +473,95 @@ export default {
return [0, 0] // 隐藏单元格 return [0, 0] // 隐藏单元格
} }
} }
}, }
handlePrev: function () {
this.$emit('prev')
},
handleSubmit: function () {
this.$refs.specForm.validate((specValid) => {
if (specValid) {
this.$refs.skuForm.validate((skuValid) => {
if (skuValid) {
this.openFullScreen()
let submitGoodsData = Object.assign({}, this.value)
delete submitGoodsData.specList
delete submitGoodsData.skuList
let specList = [] /**
this.specForm.specList.forEach(item => { * 商品表单提交
item.values.forEach(value => { */
function submitForm() {
const specForm = unref(specFormRef)
specForm.validate((specValid: boolean) => {
if (specValid) {
const skuForm = unref(skuFormRef)
skuForm.validate((skuValid: boolean) => {
if (skuValid) {
openFullScreen()
let submitsData = Object.assign({}, props.modelValue)
delete submitsData.specList
delete submitsData.skuList
let specList = [] as Array<any>
state.specForm.specList.forEach(item => {
item.values.forEach((value: any) => {
value.name = item.name value.name = item.name
}) })
specList = specList.concat(item.values) specList = specList.concat(item.values)
}) })
submitGoodsData.specList = specList // 规格列表 submitsData.specList = specList // 规格列表
submitGoodsData.price *= 100 // 金额转成分保存至数据库 submitsData.price *= 100 // 金额转成分保存至数据库
submitGoodsData.originPrice *= 100 submitsData.originPrice *= 100
let skuList = JSON.parse(JSON.stringify(this.skuForm.skuList)) let skuList = JSON.parse(JSON.stringify(state.skuForm.skuList))
skuList.map(item => { skuList.map((item: any) => {
item.price *= 100 item.price *= 100
return item return item
}) })
submitGoodsData.skuList = skuList submitsData.skuList = skuList
console.log('提交数据', submitGoodsData) console.log('提交数据', submitsData)
const goodsId = this.value.id const goodsId = props.modelValue.id
if (goodsId) { // 编辑商品提交 if (goodsId) { // 编辑商品提交
updateGoods(goodsId, submitGoodsData).then((res) => { updateGoods(goodsId, submitsData).then((res) => {
this.$router.push({path: '/pms/goods'}) router.push({path: '/pms/good'})
this.$notify.success('修改商品成功') proxy.$notify.success('修改商品成功')
this.closeFullScreen() closeFullScreen()
}, (err) => { }, (err) => {
this.closeFullScreen() closeFullScreen()
} }
) )
} else { // 新增商品提交 } else { // 新增商品提交
addGoods(submitGoodsData).then(response => { addGoods(submitsData).then(response => {
this.$router.push({path: '/pms/goods'}) router.push({path: '/pms/good'})
this.$notify.success('新增商品成功') proxy.$notify.success('新增商品成功')
this.closeFullScreen() closeFullScreen()
}, (err) => { }, (err) => {
this.closeFullScreen() closeFullScreen()
}) })
} }
} }
}) })
} }
}) })
}, }
openFullScreen: function () {
this.loading = this.$loading({
function openFullScreen() {
state.loading = proxy.$loading({
lock: true, lock: true,
text: '商品信息提交中,请等待...', text: '商品信息提交中,请等待...',
spinner: 'el-icon-loading', spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)' background: 'rgba(0, 0, 0, 0.7)'
}); });
},
closeFullScreen: function () {
if (this.loading) {
this.loading.close()
}
} }
function closeFullScreen() {
if (state.loading) {
(state.loading as any).close()
} }
} }
function handlePrev() {
/** emit('prev')
* 重写数组equals方法数组元素完全相同不论顺序
* @param target
* @returns {boolean}
*/
Array.prototype.equals = function (target) {
return this.length === target.length &&
this.every(a => target.some(b => a === b)) &&
target.every(x => this.some(y => x === y));
} }
function handNext() {
emit('next')
}
onMounted(() => {
loadData()
})
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
@@ -496,8 +582,7 @@ Array.prototype.equals = function (target) {
} }
} }
.el-form-item&#45;&#45;mini.el-form-item{ .el-form-item--mini.el-form-item {
margin-top: 18px; margin-top: 18px;
} }
</style> </style>
-->

View File

@@ -78,6 +78,7 @@ export default {
methods: { methods: {
loadData() { loadData() {
const goodsId = this.$route.query.goodsId const goodsId = this.$route.query.goodsId
console.log('goodsId',goodsId)
if (goodsId) { if (goodsId) {
getGoodsDetail(goodsId).then(response => { getGoodsDetail(goodsId).then(response => {
this.goods = response.data this.goods = response.data

View File

@@ -30,7 +30,7 @@
<el-table <el-table
v-loading="loading" v-loading="loading"
ref="multipleTable" ref="dataTableRef"
:data="pageList" :data="pageList"
@selection-change="handleSelectionChange" @selection-change="handleSelectionChange"
@row-click="handleRowClick" @row-click="handleRowClick"
@@ -87,12 +87,12 @@
<el-table-column label="操作" width="120"> <el-table-column label="操作" width="120">
<template #default="scope"> <template #default="scope">
<el-button <el-button
@click="handleUpdate(scope.row)"
type="primary" type="primary"
:icon="Edit" :icon="Edit"
size="mini" size="mini"
circle circle
plain plain
@click.stop="handleUpdate(scope.row)"
/> />
<el-button <el-button
type="danger" type="danger"
@@ -100,7 +100,7 @@
size="mini" size="mini"
circle circle
plain plain
@click="handleDelete(scope.row)" @click.stop="handleDelete(scope.row)"
/> />
</template> </template>
</el-table-column> </el-table-column>
@@ -121,12 +121,16 @@
import {Search, Plus, Edit, Refresh, Delete} from '@element-plus/icons' import {Search, Plus, Edit, Refresh, Delete} from '@element-plus/icons'
import {listGoodsWithPage, deleteGoods} from '@/api/pms/goods' import {listGoodsWithPage, deleteGoods} from '@/api/pms/goods'
import {listCascadeCategories} from '@/api/pms/category' import {listCascadeCategories} from '@/api/pms/category'
import {reactive, ref, onMounted, toRefs} from 'vue' import {reactive, ref, onMounted, toRefs, unref} from 'vue'
import {ElMessage, ElMessageBox, ElTree} from 'element-plus' import {ElTable, ElMessage, ElMessageBox, ElTree} from 'element-plus'
import {getCurrentInstance} from 'vue' import {getCurrentInstance} from 'vue'
import {moneyFormatter} from '@/utils/filter' import {moneyFormatter} from '@/utils/filter'
const {proxy}: any = getCurrentInstance(); const dataTableRef = ref(ElTable)
import {useRouter} from "vue-router"
const router=useRouter()
const state = reactive({ const state = reactive({
// 遮罩层 // 遮罩层
@@ -185,18 +189,17 @@ function resetQuery() {
handleQuery() handleQuery()
} }
function handleGoodsView(detail: any) { function handleGoodsView(detail: any) {
state.goodDetail = detail state.goodDetail = detail
state.dialogVisible = true state.dialogVisible = true
} }
function handleAdd() { function handleAdd() {
proxy.$router.push({path: 'goods-detail'}) router.push({path: 'goods-detail'})
} }
function handleUpdate(row: any) { function handleUpdate(row: any) {
proxy.$router.push({path: 'goods-detail', query: {goodsId: row.id,categoryId:row.categoryId}}) router.push({path: 'goods-detail', query: {goodsId: row.id, categoryId: row.categoryId}})
} }
function handleDelete(row: any) { function handleDelete(row: any) {
@@ -214,7 +217,7 @@ function handleDelete(row: any) {
} }
function handleRowClick(row: any) { function handleRowClick(row: any) {
proxy.$refs.multipleTable.toggleRowSelection(row); dataTableRef.value.toggleRowSelection(row);
} }
function handleSelectionChange(selection: any) { function handleSelectionChange(selection: any) {

View File

@@ -11,10 +11,8 @@
"esModuleInterop": true, "esModuleInterop": true,
"lib": ["esnext", "dom"], "lib": ["esnext", "dom"],
/* Vite */
"baseUrl": "./", "baseUrl": "./",
"paths": { "paths": {
"@": ["src"],
"@*": ["src/*"], "@*": ["src/*"],
}, },
"extends": "./tsconfig.extends.json", "extends": "./tsconfig.extends.json",