(六)商品管理模块- 商品列表功能
初始化List.vue
并添加路由
和之前的步骤类似,搭建基本的结构
<template>
<div>
<!-- 面包屑导航区域 -->
<el-breadcrumb separator-class="el-icon-arrow-right">
<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
<el-breadcrumb-item>商品管理</el-breadcrumb-item>
<el-breadcrumb-item>商品列表</el-breadcrumb-item>
</el-breadcrumb>
<!-- 卡片视图区域 -->
<el-card>
<el-row :gutter="20">
<el-col :span="8">
<el-input placeholder="请输入内容">
<el-button slot="append" icon="el-icon-search"></el-button>
</el-input>
</el-col>
<el-col :span="4">
<el-button type="primary">添加商品</el-button>
</el-col>
</el-row>
</el-card>
</div>
</template>
获取数据
然后就是编写获取数据相关的业务逻辑
data() {
return {
// 查询参数对象
queryInfo: {
query: '',
pagenum: 1,
pagesize: 10
},
// 商品列表
goodsList: [],
// 总数据条数
total: 0
}
},
created() {
this.getGoodsList()
},
methods: {
// 根据分页获取对应的商品列表
async getGoodsList() {
const { data: result } = await this.$http.get('goods', { params: this.queryInfo })
if (result.meta.status !== 200) {
return this.$message.error('获取商品列表失败!')
}
this.$message.success('获取商品列表成功!')
console.log(result.data)
this.goodsList = result.data.goods
this.total = result.data.total
}
}
显示数据
将数据展现出来
<!-- 商品table表格区域 -->
<el-table :data="goodsList" border stripe>
<el-table-column type="index"></el-table-column>
<el-table-column label="商品名称" prop="goods_name"></el-table-column>
<el-table-column label="商品价格(元)" prop="goods_price" width="90px"></el-table-column>
<el-table-column label="商品重量" prop="goods_weight" width="70px"></el-table-column>
<el-table-column label="创建时间" prop="add_time" width="140px"></el-table-column>
<el-table-column label="操作" width="130px">
<template>
<el-button type="primary" icon="el-icon-edit" size="mini"></el-button>
<el-button type="danger" icon="el-icon-delete" size="mini"></el-button>
</template>
</el-table-column>
</el-table>
使用全局过滤器Vue.filter
自定义格式化时间
main.js注册全局过滤器
Vue.filter('dateFormat', function (originVal) {
const dt = new Date(originVal)
const y = dt.getFullYear()
const m = (dt.getMonth() + 1 + '').padStart(2, '0') // 如果不是两位前面用0填充
const d = (dt.getDate() + '').padStart(2, '0')
const hh = (dt.getHours() + '').padStart(2, '0')
const mm = (dt.getMinutes() + '').padStart(2, '0')
const ss = (dt.getSeconds() + '').padStart(2, '0')
return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
})
复制代码
<el-table-column label="创建时间" prop="add_time" width="140px">
<template slot-scope="scope">
{{scope.row.add_time | dateFormat}}
</template>
</el-table-column>
商品列表分页管理功能
和之前的做法类似
搜索与清空功能
<el-col :span="8">
<el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getGoodsList">
<el-button slot="append" icon="el-icon-search" @click="getGoodsList"></el-button>
</el-input>
</el-col>
商品添加页面
通过编程式导航跳转到商品添加页面
<el-button type="primary" @click="goAddPage">添加商品</el-button>
复制代码
goAddPage(){
this.$router.push('/goods/add')
}
复制代码
创建文件goods/Add.vue 添加路由规则
渲染添加页面基本结构
<template>
<div>
<!-- 面包屑导航区域 -->
<el-breadcrumb separator-class="el-icon-arrow-right">
<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
<el-breadcrumb-item>商品管理</el-breadcrumb-item>
<el-breadcrumb-item>添加商品</el-breadcrumb-item>
</el-breadcrumb>
<!-- 卡片视图区域 -->
<el-card>
<!-- 提示区域 -->
<el-alert
title="添加商品信息"
type="info"
center
show-icon
:closable="false"
></el-alert>
<!-- 步骤条 -->
<el-steps :space="200" :active="1" finish-status="success">
<el-step title="已完成"></el-step>
<el-step title="进行中"></el-step>
<el-step title="步骤 3"></el-step>
</el-steps>
</el-card>
</div>
</template>
美化步骤条组件
<!-- 步骤条 -->
<el-steps
:space="200"
:active="activeIndex"
finish-status="success"
align-center
>
<el-step title="基本信息"></el-step>
<el-step title="商品参数"></el-step>
<el-step title="商品属性"></el-step>
<el-step title="商品图片"></el-step>
<el-step title="商品内容"></el-step>
<el-step title="完成"></el-step>
</el-steps>
复制代码
data() {
return {
activeIndex: 0
}
}
表单组成部分
<el-form
:model="addForm"
:rules="addFormRules"
ref="addFormRef"
label-width="100px"
label-position="top"
>
基本信息面板UI结构
<el-tab-pane label="基本信息" name="0">
<el-form-item label="商品名称" prop="goods_name">
<el-input v-model="addForm.goods_name"></el-input>
</el-form-item>
<el-form-item label="商品价格" prop="goods_price">
<el-input v-model="addForm.goods_price" type="number"></el-input>
</el-form-item>
<el-form-item label="商品重量" prop="goods_weight">
<el-input v-model="addForm.goods_weight" type="number"></el-input>
</el-form-item>
<el-form-item label="商品数量" prop="goods_number">
<el-input v-model="addForm.goods_number" type="number"></el-input>
</el-form-item>
<el-form-item label="商品分类" prop="goods_cat">
<el-cascader
v-model="addForm.goods_cat"
:options="cateList"
:props="cateProps"
@change="handleChange"
></el-cascader>
</el-form-item>
</el-tab-pane>
复制代码
addForm: {
goods_name: '',
goods_price: 0,
goods_weight: 0,
goods_number: 0,
// 商品所属的分类数组
goods_cat: []
},
addFormRules: {
goods_name: [
{ required: true, message: '请输入商品名称', trigger: 'blur' }
],
goods_price: [
{ required: true, message: '请输入商品价格', trigger: 'blur' }
],
goods_weight: [
{ required: true, message: '请输入商品重量', trigger: 'blur' }
],
goods_number: [
{ required: true, message: '请输入商品数量', trigger: 'blur' }
],
goods_cat: [
{ required: true, message: '请选择商品分类', trigger: 'blur' }
]
},
// 商品分类列表
cateList: [],
cateProps: {
expandTrigger: 'hover',
label: 'cat_name', // 看到的属性
value: 'cat_id', // 选中的是什么值
children: 'children' // 指定属性实现父子节点嵌套
}
复制代码
// 获取所有商品分类数据
async getCateList() {
const { data: result } = await this.$http.get('categories')
if (result.meta.status !== 200) {
return this.$message.error('获取商品分类数据失败!')
}
this.cateList = result.data
console.log(this.cateList)
},
// 级联选择器选中会触发
handleChange() {
console.log(this.addForm.goods_cat)
if (this.addForm.goods_cat.length !== 3) {
this.addForm.goods_cat = []
}
}
阻止页签切换
<el-tabs :tab-position="'left'" v-model="activeIndex" :before-leave="beforeTabLeave">
复制代码
beforeTabLeave(activeName, oldActiveName) {
if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
this.$message.error('请先选择商品分类!')
return false
}
}
获取动态参数列表数据
<el-tabs :tab-position="'left'" v-model="activeIndex" :before-leave="beforeTabLeave" @tab-click="tabClicked">
复制代码
// 动态参数列表
manyTableData: []
复制代码
async tabClicked() {
if (this.activeIndex === '1') {
const { data: result } = await this.$http.get(`categories/${this.cateId}/attributes`, {
params: { sel: 'many' }
})
if (result.meta.status !== 200) {
return this.$message.error('获取状态参数列表失败!')
}
console.log(result.data)
this.manyTableData = result.data
}
}
复制代码
computed: {
cateId() {
if (this.addForm.goods_cat.length === 3) {
return this.addForm.goods_cat[2]
}
return null
}
}
绘制商品参数面板复选框
<!-- 渲染表单item项 -->
<el-form-item
:label="item.attr_name"
v-for="item in manyTableData"
:key="item.attr_id"
>
<el-checkbox-group v-model="item.attr_vals">
<el-checkbox v-for="(cb, index) in item.attr_vals" :key="index" :label="cb" border></el-checkbox>
</el-checkbox-group>
</el-form-item>
复制代码
async tabClicked() {
if (this.activeIndex === '1') {
const { data: result } = await this.$http.get(
`categories/${this.cateId}/attributes`,
{
params: { sel: 'many' }
}
)
if (result.meta.status !== 200) {
return this.$message.error('获取状态参数列表失败!')
}
console.log(result.data)
result.data.forEach(item => {
item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
})
this.manyTableData = result.data
}
}
复制代码
.el-checkbox {
margin: 0 10px 0 0 !important;
}
图片上传功能
初步使用upload
上传组件
<!-- 图片上传模块 action表示上传的API地址 -->
<el-upload
:action="uploadURL"
:on-preview="handlePreview"
:on-remove="handleRemove"
list-type="picture"
>
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
复制代码
// 上传图片的URL地址
uploadURL: 'http://127.0.0.1:8888/api/private/v1/'
复制代码
// 处理图片预览效果
handlePreview() {},
// 处理移除图片的操作
handleRemove() {}
手动为upload
组件绑定header
请求头
el-upload组件没有使用我们定义的axios发送ajax请求
<el-upload
:action="uploadURL"
:on-preview="handlePreview"
:on-remove="handleRemove"
list-type="picture"
:headers="headerObj"
>
复制代码
// 图片上传组件的header请求头对象
headerObj: {
Authorization: window.sessionStorage.getItem('token')
}
监听upload
组件的on-success
<el-upload
:action="uploadURL"
:on-preview="handlePreview"
:on-remove="handleRemove"
list-type="picture"
:headers="headerObj"
:on-success="handleSuccess"
>
复制代码
addForm: {
goods_name: '',
goods_price: 0,
goods_weight: 0,
goods_number: 0,
// 商品所属的分类数组
goods_cat: [],
// 图片的数组
pics: []
}
复制代码
handleSuccess(responce) {
// console.log(responce)
// 1. 拼接得到一个图片信息对象
const picInfo = { pic: responce.data.temp_path }
// 2. 将图片信息对象,push到pics数组中
this.addForm.pics.push(picInfo)
}
监听upload
组件的on-remove
// 处理移除图片的操作
handleRemove(file) {
console.log(file)
// 1. 获取将要删除的图片的临时路径
const filePath = file.response.data.tmp_path
// 2. 从pics数组中,找到这个图片对应的索引值
const i = this.addForm.pics.findIndex(x => x.pic === filePath)
// 3. 调用数组的splice方法,把图片信息对象,从pics数组中移除
this.addForm.pics.splice(i, 1)
console.log(this.addForm)
}
商品内容
安装配置vue-quill-editor
富文本编辑器
安装运行依赖vue-quill-editor 3.0.6
// 商品的详情描述
goods_introduce: ''
复制代码
<!-- 富文本编辑组件 -->
<quill-editor v-model="addForm.goods_introduce"></quill-editor>
<!-- 添加商品按钮 -->
<el-button class="btnAdd" type="primary" @click="add">添加商品</el-button>
复制代码
.ql-editor {
min-height: 300px;
}
.btnAdd {
margin-top: 15px;
表单预验证
add() {
this.$refs.addFormRef.validate(valid => {
if (!valid) {
return this.$message.error('填写必要的表单项!')
}
// 执行添加的业务逻辑
})
把goods_cat
从数组传换成字符串
安装运行依赖lodash 实现深拷贝
import _ from 'lodash'
add() {
this.$refs.addFormRef.validate(valid => {
if (!valid) {
return this.$message.error('填写必要的表单项!')
}
// 执行添加的业务逻辑
const form = _.cloneDeep(this.addForm)
form.goods_cat = form.goods_cat.join(',')
})
}
处理attrs
数组
add() {
this.$refs.addFormRef.validate(valid => {
if (!valid) {
return this.$message.error('填写必要的表单项!')
}
// 执行添加的业务逻辑
const form = _.cloneDeep(this.addForm)
form.goods_cat = form.goods_cat.join(',')
// 处理动态参数
this.manyTableData.forEach(item => {
const newInfo = {
attr_id: item.attr_id,
attr_value: item.attr_vals.join(' ')
}
this.addForm.attrs.push(newInfo)
})
// 处理静态属性
this.onlyTableData.forEach(item => {
const newInfo = {
attr_id: item.attr_id,
attr_value: item.attr_vals
}
this.addForm.attrs.push(newInfo)
})
form.attrs = this.addForm.attrs
})
}
完成商品添加操作
add() {
this.$refs.addFormRef.validate(async valid => {
if (!valid) {
return this.$message.error('填写必要的表单项!')
}
// 执行添加的业务逻辑
const form = _.cloneDeep(this.addForm)
form.goods_cat = form.goods_cat.join(',')
// 处理动态参数
this.manyTableData.forEach(item => {
const newInfo = {
attr_id: item.attr_id,
attr_value: item.attr_vals.join(' ')
}
this.addForm.attrs.push(newInfo)
})
// 处理静态属性
this.onlyTableData.forEach(item => {
const newInfo = {
attr_id: item.attr_id,
attr_value: item.attr_vals
}
this.addForm.attrs.push(newInfo)
})
form.attrs = this.addForm.attrs
// 发起请求添加商品
// 商品的名称必须是唯一的
const { data: result } = await this.$http.post('goods', form)
if (result.meta.status !== 201) {
return this.$message.error('添加商品失败')
}
this.$message.success('添加商品成功')
this.$router.push('/goods')
})
}
List.vue完整代码
<template>
<div>
<!-- 面包屑导航区域 -->
<el-breadcrumb separator-class="el-icon-arrow-right">
<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
<el-breadcrumb-item>商品管理</el-breadcrumb-item>
<el-breadcrumb-item>商品列表</el-breadcrumb-item>
</el-breadcrumb>
<!-- 卡片视图区域 -->
<el-card>
<el-row :gutter="20">
<el-col :span="8">
<el-input
placeholder="请输入内容"
v-model="queryInfo.query"
clearable
@clear="getGoodsList"
>
<el-button
slot="append"
icon="el-icon-search"
@click="getGoodsList"
></el-button>
</el-input>
</el-col>
<el-col :span="4">
<el-button type="primary" @click="goAddPage">添加商品</el-button>
</el-col>
</el-row>
<!-- 商品table表格区域 -->
<el-table :data="goodsList" border stripe>
<el-table-column type="index"></el-table-column>
<el-table-column label="商品名称" prop="goods_name"></el-table-column>
<el-table-column
label="商品价格(元)"
prop="goods_price"
width="90px"
></el-table-column>
<el-table-column
label="商品重量"
prop="goods_weight"
width="70px"
></el-table-column>
<el-table-column label="创建时间" prop="add_time" width="140px">
<template slot-scope="scope">
{{ scope.row.add_time | dateFormat }}
</template>
</el-table-column>
<el-table-column label="操作" width="130px">
<template slot-scope="scope">
<el-button
type="primary"
icon="el-icon-edit"
size="mini"
></el-button>
<el-button
type="danger"
icon="el-icon-delete"
size="mini"
@click="removeById(scope.row.goods_id)"
></el-button>
</template>
</el-table-column>
</el-table>
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="queryInfo.pagenum"
:page-sizes="[5, 10, 15, 20]"
:page-size="queryInfo.pagesize"
layout="total, sizes, prev, pager, next, jumper"
:total="total"
background
>
</el-pagination>
</el-card>
</div>
</template>
<script>
export default {
data() {
return {
// 查询参数对象
queryInfo: {
query: '',
pagenum: 1,
pagesize: 10
},
// 商品列表
goodsList: [],
// 总数据条数
total: 0
}
},
created() {
this.getGoodsList()
},
methods: {
// 根据分页获取对应的商品列表
async getGoodsList() {
const { data: result } = await this.$http.get('goods', {
params: this.queryInfo
})
if (result.meta.status !== 200) {
return this.$message.error('获取商品列表失败!')
}
this.$message.success('获取商品列表成功!')
console.log(result.data)
this.goodsList = result.data.goods
this.total = result.data.total
},
handleSizeChange(newSize) {
this.queryInfo.pagesize = newSize
this.getGoodsList()
},
handleCurrentChange(newPage) {
this.queryInfo.pagenum = newPage
this.getGoodsList()
},
async removeById(id) {
const confirmResult = await this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).catch(error => error)
if (confirmResult !== 'confirm') {
return this.$message.info('已取消删除!')
}
const { data: result } = await this.$http.delete(`goods/${id}`)
if (result.meta.status !== 200) {
return this.$message.error('删除失败!')
}
this.$message.success('删除成功!')
this.getGoodsList()
},
goAddPage() {
this.$router.push('/goods/add')
}
}
}
</script>
<style scoped></style>
阅读剩余
版权声明:
作者:chun
链接:https://chun53.top/1153.html
文章版权归作者所有,未经允许请勿转载。
THE END