前端开发Vue项目实战:电商后台管理系统(七)------ 商品管理模块 --- 商品列表功能
git checkout -b goods_listgit push -u origin goods_list目录1. 初始化List.vue并 添加路由2. 商品列表table2.1 获取数据1. 初始化List.vue并 添加路由<template><div><!-- 面包屑导航区域 --><el-breadcrumb separator-class=
·
git checkout -b goods_list
git push -u origin goods_list
目录
1. 初始化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 el-col 实现栅格布局 -->
<!-- Row 组件 提供 gutter 属性来指定每一栏之间的间隔,默认间隔为 0
<el-col>里面有span属性,span为x,则分成 24/x 列(栅格布局一行分为24栏) -->
<el-row :gutter="30">
<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>
2. 商品列表table
2.1 获取数据
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
}
}
2.2 显示数据
<!-- 商品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>
2.3 使用全局过滤器Vue.filter自定义格式化时间
- main.js注册全局过滤器
//全局过滤器
//过滤器名字dataFormat,过滤器处理函数function,形参originVal是需要处理的时间数据
Vue.filter('dataFormat',function(originVal){
const dt = new Date(originVal) //给定的时间得到一个时间的日期对象
const y = dt.getFullYear() //年,是四位
const m = (dt.getMonth() + 1 + '').padStart(2,'0') //月,是从0开始需要加一,如果月份不足2位前面补0
const d = (dt.getDate() + '').padStart(2,'0') //日,是从0开始需要加一,如果月份不足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>
3. 商品列表分页管理功能
<!-- 分页区域 -->
<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>
handleSizeChange(newSize){
this.queryInfo.pagesize = newSize
//重新获取数据
this.getGoodsList()
},
handleCurrentChange(newPage){
this.queryInfo.pagenum = newPage
//重新获取数据
this.getGoodsList()
},
4. 搜索与清空功能
<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>
5. 根据ID删除商品数据
<el-button>
type="danger"
icon="el-icon-delete"
size="mini"
@click="removeById(scope.row.goods_id)"
</el-button>
async removeById(goods_id) {
const confirmResult = await this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
}).catch((error) => error)
if (confirmResult !== 'confirm') {
return this.$message.info('已取消删除')
}
const { data: res } = await this.$http.delete('goods/' + goods_id)
if (res.meta.status !== 200) {
return this.$message.error('删除商品失败!')
}
this.$message.success('删除商品成功!')
this.getGoodsList()
},
6. 商品添加页面
6.1 通过编程式导航跳转到商品添加页面
<el-button type="primary" @click="goAddPage">添加商品</el-button>
goAddPage(){
this.$router.push('/goods/add')
}
创建文件goods/Add.vue 添加路由规则
import Add from './components/goods/Add.vue'
const routes = [
{
path: '/home',
component: Home,
redirect: '/welcome',
children: [
{path: '/goods/add', component: Add },
]
},
]
6.2 渲染添加页面基本结构
<!-- 面包屑导航区域 -->
<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="300" :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>
</el-card>
data() {
return {
activeIndex: 0,
}
},
6.3 渲染tab栏区域
// 加0是拼接,减0就会转换成number类型
<el-steps :space="200" :active="activeIndex-0" >
<!-- tab栏区域: 点击第几个面板,会把第几个面板的index保存到v-model的activeIndex-->
<el-tabs :tab-position="'left'" style="height: 200px;" v-model="activeIndex">
<el-tab-pane label="基本信息" index="0">基本信息</el-tab-pane>
<el-tab-pane label="商品参数" index="1">商品参数</el-tab-pane>
<el-tab-pane label="商品属性" index="2">商品属性</el-tab-pane>
<el-tab-pane label="商品图片" index="3">商品图片</el-tab-pane>
<el-tab-pane label="商品内容" index="4">商品内容</el-tab-pane>
</el-tabs>
data() {
return {
activeIndex: '0', //默认激活第一个面板
}
},
6.4 基本信息面板UI结构
<el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top">
<el-tabs :tab-position="'left'" v-model="activeIndex">
<el-tab-pane label="基本信息" index="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>
</el-tabs>
</el-form>
data() {
return {
activeIndex: '0', //默认激活第一个面板
//添加商品的表单数据对象
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', // 指定属性实现父子节点嵌套
},
}
},
created() {
this.getCateList()
},
methods: {
//获取所有商品分类数据
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 = []
}
},
},
6.5 阻止页签切换
<el-tabs :tab-position="'left'" v-model="activeIndex" :before-leave="beforeTabLeave">
beforeTabLeave(activeName, oldActiveName) {
console.log(activeName) //即将进入的标签页index
console.log(oldActiveName) //即将离开的标签页index
//如果标签页index是0,并且当前选择的不是三级菜单--->不符合条件、不切换跳转
if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
this.$message.error('请先选择商品分类!')
return false //不跳转
}
},
6.6 获取商品参数
<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
}
}
6.7 绘制商品参数面板复选框
import { CheckboxGroup,Checkbox } from 'element-ui'
Vue.use(CheckboxGroup)
Vue.use(Checkbox)
<el-tab-pane label="商品参数" index="1">
<!-- 渲染表单的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>
</el-tab-pane>
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('获取状态参数列表失败!')
}
// 字符串转成数组
result.data.forEach((item) => {
//空字符串返回空数组
item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
})
this.manyTableData = result.data
}
},
<style lang="less" scoped>
.el-checkbox {
margin: 0 10px 0 0 !important;
}
</style>
6.8 获取静态属性列表数据
<el-tab-pane label="商品属性" index="2">
<el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
<el-input v-model="item.attr_vals"></el-input>
</el-form-item>
</el-tab-pane>
// 静态参数列表
onlyTableData: [],
async tabClicked() {
//证明访问的是动态参数面板
if (this.activeIndex === '1') {
this.manyTableData = result.data
} else if (this.activeIndex === '2') {
//证明访问的是静态参数面板
const { data: result } = await this.$http.get(`categories/${this.cateId}/attributes`, {
params: { sel: 'only' },
})
if (result.meta.status !== 200) {
return this.$message.error('获取状态参数列表失败!')
}
result.data.forEach((item) => {
item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
})
this.onlyTableData = result.data
}
},
7. 图片上传功能
7.1 初步使用upload上传组件
<el-tab-pane label="商品图片" index="3">
<!-- action图片要上传到的URL地址 -->
<el-upload :action="uploadURL" :on-preview="handlePreview" :on-remove="handleRemove" list-type="picture">
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
</el-tab-pane>
// 上传图片的URL地址
uploadURL: 'http://127.0.0.1:8888/api/private/v1/'
// 处理图片预览效果
handlePreview() {},
// 处理移除图片的操作
handleRemove() {}
7.2 手动为upload组件绑定header请求头
el-upload组件没有使用我们定义的axios发送ajax请求
<el-upload
:action="uploadURL"
:on-preview="handlePreview"
:on-remove="handleRemove"
list-type="picture"
:headers="headerObj"
>
data() {
return {
//图片上传组件的headers请求头对象
headerObj: {
Authorization: window.sessionStorage.getItem('token'),
},
}
},
7.3 监听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(response) {
// console.log(responce)
// 1. 拼接得到一个图片信息对象
const picInfo = { pic: response.data.tmp_path }
// 2. 将图片信息对象,push到pics数组中
this.addForm.pics.push(picInfo)
}
7.4 监听upload组件的on-remove
// 处理移除图片的操作
handleRemove(file) {
//1.获取将要删除图片的临时路径
const filePath = file.response.data.tmp_path
//2.从pics数组中,找到这个图片对应的索引值
//i是索引值,findIndex方法调用箭头函数,x是数组里面的每一项
const i = this.addForm.pics.findIndex((x) => x.pic === filePath)
//3.调用数组的splice方法,把图片信息对象,从pics数组中移除
this.addForm.pics.splice(i,1)
console.log(this.addForm)
},
7.5 图片预览效果
<el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
<img :src="previewPath" alt="" class="priviewImg">
</el-dialog>
data() {
return {
previewPath: '',
previewVisible:false,
}
}
// 处理图片预览效果
handlePreview(file) {
this.previewPath = file.response.data.url
this.previewVisible=true
},
8. 商品内容
8.1 安装配置vue-quill-editor富文本编辑器
安装运行依赖vue-quill-editor 3.0.6
https://github.com/surmon-china/vue-quill-editor#readme
<el-tab-pane label="商品内容" index="4">
<!-- 富文本编辑器组件 -->
<quill-editor v-model="addForm.goods_introduce"></quill-editor>
<!-- 添加商品按钮 -->
<el-button type="primary" class="btnAdd" @click="add">添加商品</el-button>
</el-tab-pane>
// 商品的详情描述
goods_introduce: ''
.ql-editor {
min-height: 300px;
}
.btnAdd {
margin-top: 15px;
}
8.2 表单预验证
//添加商品
add(){
this.$refs.addFormRef.validate(valid => {
if(!valid){
return this.$message.error('请填写必要的表单项!')
}
//执行添加的业务逻辑
})
},
8.3 把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(',')
})
}
8.4 处理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
})
},
8.5 完成商品添加操作
//添加商品
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')
})
},
9. 提交代码
git add .
git commit -m "完成商品功能开发"
git push
git checkout master
git merge goods_list
git push
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
已为社区贡献1条内容
所有评论(0)