一 点睛
1 安装 vue-quill-editor 运行依赖
2 安装 lodash 以进行深拷贝
二 代码
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 :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="230px">
<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 {
name: "List",
data() {
return {
/* 查询参数对象 */
queryInfo: {
query: '',
pagenum: 1,
pagesize: 10
},
// 商品列表
goodslist: [],
// 总数据条数
total: 0
}
},
created() {
this.getGoodsList()
},
methods: {
// 根据分页获取对应的商品列表
async getGoodsList() {
const {data: res} = await this.$http.get('goods', {params: this.queryInfo})
if (res.meta.status !== 200) {
return this.$message.error('获取商品列表失败')
}
this.$message.success('获取商品列表成功')
console.log(res.data)
this.goodslist = res.data.goods
this.total = res.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(err => err)
if (confirmResult !== 'confirm') {
return this.$message.info('已取消删除!')
}
const {data: res} = await this.$http.delete(`goods/${id}`)
if (res.meta.status !== 200) {
return this.$message.error('删除商品失败!')
}
this.$message.success('删除成功')
this.getGoodsList()
},
goAddpage(){
this.$router.push('/goods/add')
}
}
}
</script>
<style scoped>
</style>
2 新建 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="activeIndex -0" 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-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top">
<!-- tab 栏区域-->
<el-tabs :tab-position="'left'" v-model="activeIndex" :before-leave="beforeTabLeave"
@tab-click="tabClicked">
<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
expand-trigger="hover"
v-model="addForm.goods_cat"
:options="cateList"
:props="cateProps"
@change="handleChange"
clearable
change-on-select
>
</el-cascader>
</el-form-item>
</el-tab-pane>
<el-tab-pane label="商品参数" name="1">
<!-- 渲染表单的Item项 -->
<el-form-item v-for="item in manyTableData" :key="item.attr_id" :label="item.attr_name">
<!-- 复选框组 -->
<el-checkbox-group v-model="item.attr_vals">
<el-checkbox :label="cb" v-for="(cb,i) in item.attr_vals" :key="i" border></el-checkbox>
</el-checkbox-group>
</el-form-item>
</el-tab-pane>
<el-tab-pane label="商品属性" name="2">
<el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.sttr_id">
<el-input v-model="item.attr_vals"></el-input>
</el-form-item>
12
</el-tab-pane>
<el-tab-pane label="商品图片" name="3">
<!-- action 图片要上传的服务器地址
list-type :图片组件效果
-->
<el-upload
:action="uploadURL"
:on-preview="handlePreview"
:on-remove="handleRemove"
list-type="picture" :headers="headerObj" :on-success="handleSuccess">
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
</el-tab-pane>
<el-tab-pane label="商品内容" name="4">
<!-- 富文本编辑器组件 -->
<quill-editor v-model="addForm.good_introduce">
</quill-editor>
<!-- 添加商品按钮 -->
<el-button type="primary" class="btnAdd" @click="add">添加商品</el-button>
</el-tab-pane>
</el-tabs>
</el-form>
</el-card>
<!-- 图片预览 -->
<el-dialog
title="图片预览"
:visible.sync="previewVisible"
width="50%"
>
<img :src="previewPath" alt="" class="previewImg">
</el-dialog>
</div>
</template>
<script>
/* 导入 lodash */
import _ from 'lodash'
export default {
name: "Add",
data() {
return {
activeIndex: '0',
// 添加商品表单数据对象
addForm: {
goods_name: '',
goods_price: 0,
goods_weight: 0,
goods_number: 0,
// 商品所属的分类数组
goods_cat: [],
// 图片数组
pics: [],
// 商品详情描述
good_introduce: '',
// 商品的动态参数或静态属性
attrs: []
},
// 商品表单验证规则
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: {
label: 'cat_name',
value: 'cat_id',
children: 'children'
},
// 动态参数列表数组
manyTableData: [],
// 静态属性数组
onlyTableData: [],
// 上传图片的URL地址
uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
// 图片上传组件的headers请求头对象
headerObj: {
Authorization: window.sessionStorage.getItem('token')
},
previewPath: '',
previewVisible: false
}
},
created() {
this.getCateList()
},
methods: {
// 获取所有商品分类数据
async getCateList() {
const {data: res} = await this.$http.get('categories')
if (res.meta.status !== 200) {
return this.$message.error('获取商品分类失败')
}
this.cateList = res.data
console.log(this.cateList)
},
// 级联选择器选中项变化,会触发这个函数
handleChange() {
console.log(this.addForm.goods_cat)
if (this.addForm.goods_cat.length !== 3) {
this.addForm.goods_cat = []
}
},
// 切换 tab会触发该函数
beforeTabLeave(activeName, oldActiveName) {
if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
this.$message.error('请先选择商品分类')
return false
}
},
// 点击tab页签触发
async tabClicked() {
// 动态参数面板
if (this.activeIndex === '1') {
// 根据所选分类的id和当前所选的面板,获取对应的参数
const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`, {
params: {
sel: 'many'
}
})
if (res.meta.status !== 200) {
return this.$message.error('获取动态参数列表失败')
}
console.log(res.data)
res.data.forEach(item => {
item.attr_vals =
item.attr_vals.length === 0 ? [] : item.attr_vals.split(',')
})
this.manyTableData = res.data
} else if (this.activeIndex === '2') {
// 根据所选分类的id和当前所选的面板,获取对应的静态属性
const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`, {
params: {
sel: 'only'
}
})
if (res.meta.status !== 200) {
return this.$message.error('获取静态属性失败')
}
console.log(res.data)
this.onlyTableData = res.data
}
},
// 处理图片的预览效果
handlePreview(file) {
this.previewPath = file.response.data.url
this.previewVisible = true
},
// 处理移除图片的操作
handleRemove(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)
},
// 监听图片上传成功的事件
handleSuccess(response) {
console.log('')
// 1 拼接得到一个图片信息对象
const picInfo = {
pic:
response.data.tmp_path
}
// 2 将图片信息对象 保存到 pics
this.addForm.pics.push(picInfo)
console.log(this.addForm)
},
// 添加商品
add() {
this.$refs.addFormRef.validate(async valid => {
// 添加表单预验证
if (!valid) {
return this.$message.error('请填写必要的表单项!')
}
// 执行添加业务逻辑
// lodash cloneDeep(obj)
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
console.log(form)
// 发起请求添加商品
// 商品的名称,必须是唯一的
const {data: res} = await this.$http.post('goods', form)
if (res.meta.status !== 201) {
this.$message.error('添加商品失败!')
}
this.$message.success('添加商品成功!')
this.$router.push('/goods')
})
}
},
computed: {
// 当前选中的三级分类的Id
cateId() {
if (this.addForm.goods_cat.length === 3) {
return this.addForm.goods_cat[2]
}
return null
}
}
}
</script>
<style scoped>
.el-checkbox {
margin: 0 10px 0 0 !important;
}
.previewImg {
width: 100%;
}
.btnAdd {
margin-top: 15px;
}
</style>
3 修改路由 index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入登录组件
import Login from "../components/Login";
// 导入Home 组件
import Home from "../components/Home";
// 导入Welcome 组件
import Welcome from "../components/Welcome";
// 导入 Users 组件
import Users from "../components/user/Users";
// 导入权限列表 组件
import Rights from "../components/power/Rights";
// 导入角色列表 组件
import Roles from "../components/power/Roles";
// 导入商品分类 组件
import Cate from "../components/goods/Cate";
// 导入商品分类参数 组件
import Params from "../components/goods/Params";
// 导入商品列表组件
import GoodsList from "../components/goods/List";
// 导入增加商品名称组件
import Add from "../components/goods/Add";
import {renderThumbStyle} from "element-ui/packages/scrollbar/src/util";
Vue.use(VueRouter)
const routes = [
// 路由重定向,当访问/,就会重定向到/login
{
path: '/',
redirect: '/login'
},
// 定义登录路由规则
{
path: '/login',
component: Login
},
// 定义Home的路由规则
{
path: '/home',
component: Home,
redirect: '/welcome',
children: [
{
path: '/welcome',
component: Welcome
},
/* 用户管理 */
{
path: '/users',
component: Users
},
/* 权限管理 */
{
path: '/rights',
component: Rights
},
/* 角色管理 */
{
path: '/roles',
component: Roles
},
/* 商品分类 */
{
path: '/categories',
component: Cate
},
/* 商品分类参数 */
{
path: '/params',
component: Params
},
/* 商品列表 */
{
path: '/goods',
component: GoodsList
},
/* 增加商品 */
{
path: '/goods/add',
component: Add
},
]
}
]
const router = new VueRouter({
routes
})
// 挂载路由导航守卫
// to 将要访问的路径
// from 代表从哪个路径跳转而来
// next 是个函数,表示放行 next() 放行 next('/login') 强制跳转
router.beforeEach((to, from, next) => {
// 如果用户访问的登录页,直接放行
if (to.path === '/login') return next();
// 从 sessionStorage 中获取到保存的 token 值
const tokenstr = window.sessionStorage.getItem('token')
// 没有 token,强制跳转到登录页
if (!tokenstr) return next('/login')
next()
})
export default router
4 修改element.js
import Vue from 'vue'
// 按需分配各个组件
import {
Button,
Form,
FormItem,
Input,
Message,
Container,
Header,
Aside,
Main,
Menu,
Submenu,
MenuItem,
Breadcrumb,
BreadcrumbItem,
Card,
Row,
Col,
Table,
TableColumn,
Switch,
Tooltip,
Pagination,
Dialog,
MessageBox,
Tag,
Tree,
Select,
Option,
Cascader,
Alert,
Tabs,
TabPane,
Steps,
Step,
CheckboxGroup,
Checkbox,
Upload
} from 'element-ui'
Vue.use(Button)
Vue.use(Form)
Vue.use(FormItem)
Vue.use(Input)
Vue.use(Container)
Vue.use(Header)
Vue.use(Aside)
Vue.use(Main)
Vue.use(Menu)
Vue.use(Submenu)
Vue.use(MenuItem)
Vue.use(Breadcrumb)
Vue.use(BreadcrumbItem)
Vue.use(Card)
Vue.use(Row)
Vue.use(Col)
Vue.use(Table)
Vue.use(TableColumn)
Vue.use(Switch)
Vue.use(Tooltip)
Vue.use(Pagination)
Vue.use(Dialog)
Vue.use(Tag)
Vue.use(Tree)
Vue.use(Select)
Vue.use(Option)
Vue.use(Cascader)
Vue.use(Alert)
Vue.use(Tabs)
Vue.use(TabPane)
Vue.use(Step)
Vue.use(Steps)
Vue.use(CheckboxGroup)
Vue.use(Checkbox)
Vue.use(Upload)
// 这里和其他组件不一样,需要通过 prototype 全局挂载 Message
Vue.prototype.$message = Message
Vue.prototype.$confirm = MessageBox.confirm
5 修改global.css
/* 全局样式 */
/* 撑满全屏 */
html, body, #app {
height: 100%;
margin: 0;
padding: 0;
}
.el-breadcrumb {
margin-bottom: 15px;
font-size: 12px;
}
/* 设置卡片阴影 */
.el-card {
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;
}
.el-table {
margin-top: 15px;
font-size: 12px;
}
.el-pagination {
margin-top: 15px;
}
.el-tag {
margin: 7px;
}
.bdtop {
border-top: 1px solid #eee;
}
.bdbottom {
border-bottom: 2px solid #eee;
}
.el-steps{
margin: 15px 0;
}
.el-step__title{
font-size: 13px;
}
.ql-editor{
min-height: 300px;
}
6 修改 main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import './plugins/element.js'
// 导入阿里的字体图标
import './assets/fonts/iconfont.css'
// 导入全局样式表,使得全局样式生效
import './assets/css/global.css'
// 全局导入axios
import axios from 'axios'
// 导入TreeTable 插件
import TreeTable from 'vue-table-with-tree-grid'
// 导入富文本编辑器组件
import VueQuillEditor from 'vue-quill-editor'
// 导入富文本编辑器对应的样式
import 'quill/dist/quill.core.css' // import styles
import 'quill/dist/quill.snow.css' // for snow theme
import 'quill/dist/quill.bubble.css' // for bubble theme
// 设置axios请求的根路径
axios.defaults.baseURL = 'http://127.0.0.1:8888/api/private/v1/'
// axios请求拦截
axios.interceptors.request.use(config => {
// 为请求头对象,添加 Token 验证的 Authorization 字段
config.headers.Authorization = window.sessionStorage.getItem('token')
return config
})
Vue.prototype.$http = axios
Vue.config.productionTip = false
// 注册 TreeTable 组件
Vue.component('tree-table', TreeTable)
// 注册 富文本编辑器 组件为全局可用组件
Vue.use(VueQuillEditor)
// 添加时间过滤器
Vue.filter('dateFormat', function (originVal) {
const dt = new Date(originVal)
const y = dt.getFullYear()
const m = (dt.getMonth() + 1 + '').padStart(2, '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}`
})
new Vue({
router,
render: h => h(App)
}).$mount('#app')
三 效果