git checkout -b goods_list
git push -u origin goods_list
<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>
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>
//全局过滤器
//过滤器名字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>
<!-- 分页区域 -->
<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()
},
<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="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()
},
<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 },
]
},
]
<!-- 面包屑导航区域 -->
<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,
}
},
// 加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', //默认激活第一个面板
}
},
<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 = []
}
},
},
<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 //不跳转
}
},
<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
}
}
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>
<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
}
},
<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() {}
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'),
},
}
},
<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)
}
// 处理移除图片的操作
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)
},
<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
},
安装运行依赖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;
}
//添加商品
add(){
this.$refs.addFormRef.validate(valid => {
if(!valid){
return this.$message.error('请填写必要的表单项!')
}
//执行添加的业务逻辑
})
},
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(',')
})
}
//添加商品
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')
})
},
git add .
git commit -m "完成商品功能开发"
git push
git checkout master
git merge goods_list
git push