【Vue】实战项目:电商后台管理系统(四)商品管理模块-商品分类功能

2,052 阅读4分钟

嗨!~ 大家好,我是YK菌 🐷 ,一个微系前端 ✨,爱思考,爱总结,爱记录,爱分享 🏹,欢迎关注我呀 😘 ~ [微信号: yk2012yk2012,微信公众号:ykyk2012]

「这是我参与11月更文挑战的第10天,活动详情查看:2021最后一次更文挑战

项目地址:https://gitee.com/ykang2020/vue_shop

今天完成商城后台管理系统的商品管理模块的第一部分:商品分类。主要是学习如何从后端获取数据,然后呈现在前端页面中。

1 介绍

商品分类用于在购物时,快速找到所要购买的商品,可以通过电商平台主页直观的看到

在这里插入图片描述

2 创建git分支

git checkout -b goods_cate
git push -u origin goods_cate

3 通过路由加载商品分类组件

创建组件 components/goods/Cate.vue并通过路由组件挂载到页面中

4 绘制商品分类组件的基本页面布局

<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>
        <el-button type="primary">添加分类</el-button>
      </el-col>
    </el-row>
    <!-- 表格区域 -->

    <!-- 分页区域 -->
    
  </el-card>
</div>

5 调用API获取商品分类列表数据

在这里插入图片描述

  data() {
    return {
      // 查询条件
      querInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 商品分类的数据列表
      cateList: [],
      // 总数据条数
      total: 0
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取商品分类数据
    async getCateList() {
      const { data: result } = await this.$http.get('categories', {params: this.querInfo})
      if (result.meta.status !== 200) {
        return this.$message.error('获取商品分类失败!')
      }
      // 把数据列表赋值给cateList
      this.cateList = result.data.result
      // 为总数据条数赋值
      this.total = result.data.total
    }
  }

6 使用vue-table-with-tree-grid树形表格组件

  1. 安装依赖-运行依赖 vue-table-with-tree-grid 使用说明

  2. main.js中导入插件

import TreeTable from 'vue-table-with-tree-grid'

Vue.component('tree-table', TreeTable)
  1. 使用组件展示分类数据
<!-- 分类表格
:data(设置数据源) :columns(设置表格中列配置信息) :selection-type(是否有复选框)
:expand-type(是否展开数据) show-index(是否设置索引列) index-text(设置索引列头)
border(是否添加纵向边框) :show-row-hover(是否鼠标悬停高亮) -->
<tree-table :data="cateList" :columns="columns" :selection-type="false"
:expand-type="false" show-index index-text="#" border :show-row-hover="false" class="treetable">

</tree-table>
  1. 在数据中添加columns
// 在数据中添加columns:
columns: [
    {label:'分类名称',prop:'cat_name'}
]
  1. 设置表格与按钮之间的间距
.treetable{
  margin-top: 15px;
}

7 使用自定义模板渲染表格数据列

<tree-table>
  <!-- 是否有效 -->
  <template slot="isok" slot-scope="scope">
    <i class="el-icon-success" v-if="scope.row.cat_deleted===false" style="color: lightgreen"></i>
    <i class="el-icon-error" v-else style="color: red"></i>
  </template>
</tree-table>
columns: [
  {
    label: '是否有效',
    // 表示将当前列定义为模板列
    type: 'template',
    // 表示当前这一列使用模板名称
    template: 'isok'
  }
]

8 渲染排序和操作对应的UI结构

<tree-table>
  <!-- 排序 -->
  <template slot="order" slot-scope="scope">
    <i class="el-icon-success" v-if="scope.row.cat_deleted===false" style="color: lightgreen"></i>
    <i class="el-icon-error" v-else style="color: red"></i>
  </template>
  <!-- 操作 -->
  <template slot="opt">
    <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>
</tree-table>
columns: [
  {
    label: '排序',
    // 表示将当前列定义为模板列
    type: 'template',
    // 表示当前这一列使用模板名称
    template: 'order'
  },
  {
    label: '操作',
    // 表示将当前列定义为模板列
    type: 'template',
    // 表示当前这一列使用模板名称
    template: 'opt'
  }
]

9 实现分页功能

<!-- 分页区域 -->
<el-pagination
  @size-change="handleSizeChange"
  @current-change="handleCurrentChange"
  :current-page="queryInfo.pagenum"
  :page-sizes="[3, 5, 10, 15]"
  :page-size="queryInfo.pagesize"
  layout="total, sizes, prev, pager, next, jumper"
  :total="total">
</el-pagination>
// 监听pagesize改变的事件
handleSizeChange(newSize) {
  this.queryInfo.pagesize = newSize
  // 刷新数据
  this.getCateList()
},
// 监听pagenum改变的事件
handleCurrentChange(newPage) {
  this.queryInfo.pagenum = newPage
  this.getCateList()
}

10 渲染添加分类的对话框和表单

 <el-button type="primary" @click="showAddCatDialog">添加分类</el-button>
<!-- 添加分类对话框 -->
<el-dialog
  title="添加分类"
  :visible.sync="addCateDialogVisible"
  width="50%">
  <!-- 添加分类的表单 -->
  <el-form :model="addCateForm" :rules="addCateFormRules" ref="addCateFormRef" label-width="100px">
    <el-form-item label="分类名称:" prop="cat_name">
      <el-input v-model="addCateForm.cat_name"></el-input>
    </el-form-item>
    <el-form-item label="父级分类:" >
      
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addCateDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addCateDialogVisible = false">确 定</el-button>
  </span>
</el-dialog>
// 控制添加分类对话框的显示与隐藏
addCateDialogVisible: false,
// 添加分类的表单数据对象
addCateForm: {
  // 将要添加分类的名称
  cat_name: '',
  // 父级分类的id
  cat_pid: 0,
  // 分类的等级,默认添加的是一级分类
  cat_level: 0
},
// 添加分类表单的验证规则对象
addCateFormRules: {
  cat_name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' }
  ]      
}
// 点击按钮,显示对话框
showAddCatDialog() {
  this.addCateDialogVisible = true
}

11 获取父级分类数据列表

// 父级分类的列表
parentCateList: []
// 点击按钮,显示对话框
showAddCatDialog() {
  // 先获取父级分类的数据列表
  this.getParentCateList()
  // 再展示对话框
  this.addCateDialogVisible = true
},
// 获取父级分类的数据列表
async getParentCateList() {
  const { data: result } = await this.$http.get('categories', { params: { type: 2 } })
  if (result.meta.status !== 200) {
    return this.$message.error('获取父级分类数据失败!')
  }
  this.parentCateList = result.data
}

12 渲染级联选择器

<el-form-item label="父级分类:" >
    <el-cascader
      v-model="selectedKeys"
      :options="parentCateList"
      :props="cascaderProps"
      @change="parentCateChanged"
      clearable></el-cascader>
</el-form-item>
  // 父级分类的列表
  parentCateList: [],
  // 指定级联选择器的配置对象
  cascaderProps: {
    expandTrigger: 'hover',
    value: 'cat_id',
    label: 'cat_name',
    children: 'children',
    checkStrictly: true
  },
  // 选中的父级分类的id数组
  selectedKeys: []
// 选择项发生变化触发
parentCateChanged() {
  console.log(this.selectedKeys)
}

13 根据父分类的变化处理表单中数据

<el-button type="primary" @click="addCate">确 定</el-button>
// 选择项发生变化触发
parentCateChanged() {
  // console.log(this.selectedKeys)

  // 如果selectedKeys数组中的length大于0,证明选中的父级分类
  if (this.selectedKeys.length > 0) {
    // 父级分类的id
    this.addCateForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
    // 为当前分类的等级赋值
    this.addCateForm.cat_level = this.selectedKeys.length
  } else { // 反之,就说明没有选中任何父级分类
    this.addCateForm.cat_pid = 0
    this.addCateForm.cat_level = 0
  }
}
// 点击确定按钮添加新的分类
addCate() {
  console.log(this.addCateForm)
}

14 在对话框的close事件中重置表单数据

<!-- 添加分类对话框 -->
<el-dialog
  title="添加分类"
  :visible.sync="addCateDialogVisible"
  width="50%"
  @close="addCateDialogClosed">
// 监听对话框的关闭事件,重置表单数据
addCateDialogClosed() {
  this.$refs.addCateFormRef.resetFields()
  this.selectedKeys = []
  this.addCateForm.cat_level = 0
  this.addCateForm.cat_pid = 0
}

15 完成添加分类操作

// 点击确定按钮添加新的分类
addCate() {
  // console.log(this.addCateForm)
  this.$refs.addCateFormRef.validate(async valid => {
    if (!valid) return this.$message.error('表单预校验失败!')
    const { data: result } = await this.$http.post(
      'categories',
      this.addCateForm
    )
    if (result.meta.status !== 201) {
      return this.$message.error('添加分类失败!')
    }
    this.$message.success('添加分类成功')
    // 刷新列表
    this.getCateList()
    // 隐藏对话框
    this.addCateDialogVisible = false
  })
}

16 完成编辑和删除的操作

编辑

  1. 展示修改用户的对话框

  2. 根据id查询对应的分类信息 在这里插入图片描述

  3. 渲染修改分类的表单

  4. 修改分类表单的重置操作

  5. 提交表单预验证及完成分类信息的修改 在这里插入图片描述

删除

  1. 弹框询问用户是否确认删除

  2. 调用API完成删除分类操作 在这里插入图片描述

参考【Vue】实战项目:电商后台管理系统(Element-UI)(二)用户管理模块

17 Cate.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>
          <el-button type="primary" @click="showAddCatDialog"
            >添加分类</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格区域 :data(设置数据源) :columns(设置表格中列配置信息) :selection-type(是否有复选框) :expand-type(是否展开数据) show-index(是否设置索引列) index-text(设置索引列头) border(是否添加纵向边框) :show-row-hover(是否鼠标悬停高亮) -->
      <tree-table
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text=""
        border
        class="treetable"
      >
        <!-- 是否有效 -->
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: lightgreen"
          ></i>
          <i class="el-icon-error" v-else style="color: red"></i>
        </template>

        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag
            type="success"
            size="mini"
            v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag type="warning" size="mini" v-else>三级</el-tag>
        </template>

        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="showEditDialog(scope.row.cat_id)"
            >编辑</el-button
          >
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeCateById(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="addCateDialogClosed"
    >
      <!-- 添加分类的表单 -->
      <el-form
        :model="addCateForm"
        :rules="addCateFormRules"
        ref="addCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称:" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类:">
          <el-cascader
            v-model="selectedKeys"
            :options="parentCateList"
            :props="cascaderProps"
            @change="parentCateChanged"
            clearable
            change-on-select
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改分类名称的对话框 -->
    <el-dialog
      title="修改分类"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="editCateForm"
        :rules="addCateFormRules"
        ref="editCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称:" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCateInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 查询条件
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 商品分类的数据列表
      cateList: [],
      // 总数据条数
      total: 0,
      // 为table指定列的定义,在数据中添加columns
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name' // 对应列内容的属性名称
        },
        {
          label: '是否有效',
          // 表示将当前列定义为模板列
          type: 'template',
          // 表示当前这一列使用模板名称
          template: 'isok'
        },
        {
          label: '排序',
          // 表示将当前列定义为模板列
          type: 'template',
          // 表示当前这一列使用模板名称
          template: 'order'
        },
        {
          label: '操作',
          // 表示将当前列定义为模板列
          type: 'template',
          // 表示当前这一列使用模板名称
          template: 'opt'
        }
      ],
      // 控制添加分类对话框的显示与隐藏
      addCateDialogVisible: false,
      // 添加分类的表单数据对象
      addCateForm: {
        // 将要添加分类的名称
        cat_name: '',
        // 父级分类的id
        cat_pid: 0,
        // 分类的等级,默认添加的是一级分类
        cat_level: 0
      },
      // 添加分类表单的验证规则对象
      addCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      // 父级分类的列表
      parentCateList: [],
      // 指定级联选择器的配置对象
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true
      },
      // 选中的父级分类的id数组
      selectedKeys: [],
      // 控制修改分类名称对话框的显示与隐藏
      editDialogVisible: false,
      editCateForm: {}
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取商品分类数据
    async getCateList() {
      const { data: result } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (result.meta.status !== 200) {
        return this.$message.error('获取商品分类失败!')
      }
      // 把数据列表赋值给cateList
      // console.log(result)
      console.log(result.data)
      this.cateList = result.data.result
      // 为总数据条数赋值
      // console.log(result.total)
      this.total = result.data.total
    },
    // 监听pagesize改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      // 刷新数据
      this.getCateList()
    },
    // 监听pagenum改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getCateList()
    },
    // 点击按钮,显示对话框
    showAddCatDialog() {
      // 先获取父级分类的数据列表
      this.getParentCateList()
      // 再展示对话框
      this.addCateDialogVisible = true
    },
    // 获取父级分类的数据列表
    async getParentCateList() {
      const { data: result } = await this.$http.get('categories', {
        params: { type: 2 }
      })
      if (result.meta.status !== 200) {
        return this.$message.error('获取父级分类数据失败!')
      }
      this.parentCateList = result.data
    },
    // 选择项发生变化触发
    parentCateChanged() {
      // console.log(this.selectedKeys)

      // 如果selectedKeys数组中的length大于0,证明选中的父级分类
      if (this.selectedKeys.length > 0) {
        // 父级分类的id
        this.addCateForm.cat_pid = this.selectedKeys[
          this.selectedKeys.length - 1
        ]
        // 为当前分类的等级赋值
        this.addCateForm.cat_level = this.selectedKeys.length
      } else {
        // 反之,就说明没有选中任何父级分类
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
      }
    },
    // 点击确定按钮添加新的分类
    addCate() {
      // console.log(this.addCateForm)
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) return this.$message.error('表单预校验失败!')
        const { data: result } = await this.$http.post(
          'categories',
          this.addCateForm
        )
        if (result.meta.status !== 201) {
          return this.$message.error('添加分类失败!')
        }
        this.$message.success('添加分类成功')
        // 刷新列表
        this.getCateList()
        // 隐藏对话框
        this.addCateDialogVisible = false
      })
    },
    // 监听对话框的关闭事件,重置表单数据
    addCateDialogClosed() {
      this.$refs.addCateFormRef.resetFields()
      this.selectedKeys = []
      this.addCateForm.cat_level = 0
      this.addCateForm.cat_pid = 0
    },
    // 展示编辑分类名称的对话框
    async showEditDialog(id) {
      this.editDialogVisible = true
      const { data: result } = await this.$http.get(`categories/${id}`)
      if (result.meta.status !== 200) {
        return this.$message.error('查询分类数据失败!')
      }
      console.log(result.data)
      this.editCateForm = result.data
    },
    // 监听修改分类名称对话框的关闭事件
    editDialogClosed() {
      this.$refs.editCateFormRef.resetFields()
    },
    // 修改分类名称信息,并提交
    editCateInfo() {
      this.$refs.editCateFormRef.validate(async valid => {
        if (!valid) return
        // 发起修改分类名称的数据请求
        const { data: result } = await this.$http.put(`categories/${this.editCateForm.cat_id}`, { cat_name: this.editCateForm.cat_name })
        if (result.meta.status !== 200) return this.$message.error('更新分类名称失败!')
        // 关闭对话框
        this.editDialogVisible = false
        // 重新获取用户列表
        this.getCateList()
        // 提示修改成功
        this.$message.success('更新分类名称成功!')
      })
    },
    async removeCateById(id) {
      // 弹框提示用户是否删除数据
      const confirmResult = await this.$confirm('此操作将永久删除该分类,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      // console.log(confirmResult) // 确定:'confirm' 取消:报错:cancel catch之后就是'canel'
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      const { data: result } = await this.$http.delete('categories/' + id)
      if (result.meta.status !== 200) {
        return this.$message.error('删除分类失败')
      }
      this.$message.success('删除分类成功')
      this.getCateList()
    }
  }
}
</script>

<style scoped>
.treetable {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}
</style>

18 提交代码

git branch

* goods_cate
git add .
git commit -m "完成了分类功能的开发"
git push
git checkout master
git merge goods_cate 
git push

项目地址:https://gitee.com/ykang2020/vue_shop

最后,欢迎关注我的专栏,和YK菌做好朋友!