2020 零基础到快速开发 Vue全家桶开发电商管理系统(六)

分类参数篇

分类参数

创建分支

git checkout -b goods_params
git push -u origin goods_params

1 通过路由加载分类参数组件页面

//goods下建Params.vue

//index.js(router)
import Params from '../components/goods/Params'
{ path: '/params', component: Params }

2 渲染分类参数页面的基本UI结构

//Params.vue
//<!-- 面包屑导航区 -->
    <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="warning" show-icon :closable="false">
    </el-alert>
 //    <!-- 选择商品分类区域 -->
     <el-row :gutter="10" class="cat_opt">
       <el-col :span="6">
         <span>选择商品分类:</span>
     //    <!-- 选择商品分类的级联选择框 -->
       </el-col>
     </el-row>
    </el-card>
    
.cat_opt{ margin: 15px 0;}

//element.js
import { Alert } from 'element-ui'
Vue.use(Alert)

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

data() {  catelist: [] }  },
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
    }
}

4 渲染商品分类的级联选择框

 <el-cascader  v-model="selectedCateKeys" :options="catelist" :props="cateProps"  @change="handleChange"></el-cascader>
 data() { 
    return {
       // 商品分类列表
      catelist: [],
      // 级联选择框配置对象
      cateProps:{
         expandTrigger: 'hover',
         value:'cat_id',
         label:'cat_name',
         children:'children'
      },
      // 级联选择框双向绑定到的数组
      selectedCateKeys:[]
    }
 } 
 methods: {
 // 级联选择框选中项变化会触发这个函数
    handleChange() {  console.log(this.selectedCateKeys); }

5 控制级联选择框的选中范围

handleChange() {
      console.log(this.selectedCateKeys)
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        return
      }
      console.log(this.selectedCateKeys)
    }

6 渲染分类参数的Tabs页签

<!-- tab 页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">动态参数</el-tab-pane>
        <el-tab-pane label="静态属性" name="only">静态属性</el-tab-pane> 
      </el-tabs>
  data() {  return { activeName:'many' } }  // 被激活的页签名称
  methods: { handleTabClick() { console.log(this.activeName); }  // tab页签点击事件处理函数

//element.js
import { Tabs,TabPane } from 'element-ui'
Vue.use(Tabs)
Vue.use(TabPane)

7 渲染添加参数按钮并控制按钮的禁用状态

 <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled">添加参数</el-button>
        </el-tab-pane>
        <!-- 添加静态属性的面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled">添加属性</el-button>
        </el-tab-pane>
 
computed: {
    // 如果按钮需要被禁用,返回true
    isBtnDisabled() {
      if ((this.selectedCateKeys.length !== 3)) { return true }
      return false
    }  

8 获取参数列表数据

9 将获取到的参数数据挂载到不同的数据源上

1.级联选择器选择项发生变化时获取
2.切换Tab面时获取

data() {
  return{  
       // 动态参数数据
      manyTableData: [],
      // 静态属性数据
      onlyTableData: []
      }
  }
methods:{
// 级联选择框选中项变化会触发这个函数
    handleChange() { this.getParamsData() },
// tab页签点击事件处理函数
    handleTabClick() {
     // console.log(this.activeName)
      this.getParamsData()
    },
// 获取参数列表数据
    async getParamsData() {
      console.log(this.selectedCateKeys)
      if (this.selectedCateKeys.length !== 3) { this.selectedCateKeys = []   return }
      console.log(this.selectedCateKeys)
      const { data: res } = await this.$http.get( `categories/${this.cateId}/attributes`,
                                    { params: { sel: this.activeName }})
      if (res.meta.status != 200) { return this.$message.error("获取参数列表失败!") }
     // console.log(res.data)
      if (this.activeName == "many") { this.manyTableData = res.data } 
      else { this.onlyTableData = res.data }
    }
 }

10 渲染动态参数和静态属性的Table表格

<!-- 动态 -->
<el-table :data="manyTableData" border stripe>
            <el-table-column type="expand"></el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <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">删除</el-button>
              </template>
            </el-table-column>
  </el-table>
  
<!-- 静态 -->
<el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand"></el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <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">删除</el-button>
              </template>
            </el-table-column>
 </el-table>

11 完成动态参数和静态属性的添加操作

<el-button  @click="addDialogVisible = true">添加参数</el-button>
<el-button  @click="addDialogVisible = true">添加属性</el-button>

<!-- 添加参数对话框 -->
    <el-dialog :title="'添加' + titleText" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed" >
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addDialogVisible = false">确 定</el-button>
      </span>
  </el-dialog>

data() {
    return {
       // 控制添加对话框的显示与隐藏
      addDialogVisible: false,
      // 添加参数的表单数据对象
      addForm: {},
      // 添加表单的验证规则对象
      addFormRules: {
        attr_name: [ { required: true, message: "请输入参数名称", trigger: "blur" } ]
      }
    },

computed: { 
    titleText() {
      if (this.activeName == "many") { return "动态参数" }
      return "静态属性"
    }
  },
methods: {
   // 监听添加对话框的关闭事件
    addDialogClosed() { this.$refs.addFormRef.resetFields() }
} 
 <el-button type="primary" @click="addParams">确 定</el-button>
 methods: { 
    // 点击确定,添加参数
    addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
       const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`,{
          attr_name:this.addForm.attr_name,
          attr_sel:this.activeName
        })
        if(res.meta.status!=201){
          this.$message.error('添加参数失败!')
        }
        this.$message.success("添加参数成功!")
        this.addDialogVisible = false
        this.getParamsData()
      })
    }

12 渲染修改参数的对话框

选中要替换的内容 一直 ctrl+d (批量替换)

<el-button  @click="showEditDialog">编辑</el-button>   //动态
<el-button  @click="showEditDialog">编辑</el-button>   //静态
<!-- 修改参数对话框 -->
    <el-dialog :title="'修改' + titleText" :visible.sync="editDialogVisible"  width="50%" @close="editDialogClosed" >
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_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="editParams">确 定</el-button>
      </span>
    </el-dialog> 

在这里插入图片描述
在这里插入图片描述

13 完成修改参数的操作

<el-button  @click="showEditDialog(scope.row.attr_id)">编辑</el-button>   //动态
<el-button  @click="showEditDialog(scope.row.attr_id)">编辑</el-button>   //静态

methods:{
  //展示修改对话框
    async showEditDialog(attr_id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        { params: { attr_sel: this.activeName } }
      )
      console.log(res)
      if (res.meta.status != 200) {
        return this.$message.error("获取参数信息失败!")
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 点击确定,修改参数
    editParams() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status != 200) {
          this.$message.error("修改参数失败!")
        }
        this.$message.success("修改参数成功!")
        this.editDialogVisible = false
        this.getParamsData()
      })
    }

  

14 完成删除参数的业务逻辑

 <el-button @click="removeParams(scope.row.attr_id)">删除</el-button>
 // 根据id删除对应数据项
    async removeParams(attr_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(
        `categories/${this.cateId}/attributes/${attr_id}`
      )
      if (res.meta.status != 200) {
        return this.$message.error("删除参数失败!")
      }
      this.$message.success("删除参数成功!")
      this.getParamsData()
    }

15 渲染参数下的可选项

本来是字符串,转化为数组再 forEach 循环遍历渲染
在这里插入图片描述
转换后
在这里插入图片描述
在这里插入图片描述

<el-table-column type="expand">
     <template slot-scope="scope"> 
         <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable>{{item}}</el-tag>
     </template>
</el-table-column>

 methods: {
   // 获取参数列表数据
    async getParamsData() {
     .......
      if (res.meta.status != 200) {..... }
      //获取成功
     res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : []  //没有的话直接是个空数组
      })
      console.log(res.data)
      ....

16 实现控制按钮与文本框的切换显示

<el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue"  ref="saveTagInput" size="small"
        @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm" ></el-input>
 <el-button class="button-new-tag" v-else  size="small" @click="showInput">+ New Tag</el-button>
data() {
    return {
      inputVisible:false,
      inputValue: ''
    }
 },
methods: {
   // 文本框失去焦点或按下回车触发
    handleInputConfirm() { console.log("ok"); },
    // 点击按钮,展示文本输入框
    showInput() { this.inputVisible=true }
  }

.input-new-tag{ width: 120px; }

解决不同行互相联动bug:单独提供自己的inputVisible,inputValue
文本框自动获得焦点

<el-input  v-if="scope.row.inputVisible" v-model="scope.row.inputValue"></el-input>
<el-button  @click="showInput(scope.row)">+ New Tag</el-button>

//去掉data 中的inputVisible,inputValue
methods: {
// 获取参数列表数据
 async getParamsData() { 
   .......
    res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : []
        // 控制按钮与文本框切换显示
        item.inputVisible = false
        // 文本框输入的内容
        item.inputValue = ""
    }),
 showInput(row) {  
    row.inputVisible = true 
    // 让文本框自动获得焦点
    // $nextTick方法的作用:当页面上元素被重新渲染后,才执行回调函数中的代码
      this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    }     
}

失去焦点/回车立即切换回Tag标签

<el-input @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"></el-input>
methods: {
   handleInputConfirm(row) {row.inputVisible = false},
}

17 完成参数可选项的添加操作

// 文本框失去焦点或按下回车触发
    async handleInputConfirm(row) {
      //1.(优化)没输入/输入的是空格
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ""
        row.inputVisible = false
        return
      }
      //2. 输入了内容
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ""
      row.inputVisible = false
      // 3.需要发起请求,保存这次操作
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(",")
        }
      )
      if (res.meta.status != 200) {
        this.$message.error("修改参数项失败!")
      }
      this.$message.success("修改参数项成功!")
    },

18 删除参数下的可选项

<el-tag @close="handleClosed(i, scope.row)">{{ item }}</el-tag>
methods:{
   // 文本框失去焦点或按下回车触发
    async handleInputConfirm(row) {
      .....
      // 需要发起请求,保存这次操作
      this.saveAttrVals(row)
   }
   // 将对 attr_vals的操作保存到数据库(把上边第 3 步,单独抽出来封装成一个方法)
   async saveAttrVals(row) { ....}
   
    // 删除对应的参数可选项
    handleClosed(i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    }
}

19 清空表格数据

解决当添加参数为禁用状态下,表格依旧存在的问题,我们需要对此进行清空
在这里插入图片描述

20 完成静态属性表格中展开行的效果

只需要把之前在动态参数写过的 展开项 的代码直接复制一份到静态属性展开行即可(通用)。
在这里插入图片描述

提交码云

git branch  #(goods_params)
git status
git add .
git commit -m "完成了分类参数的开发"
git push
git checkout master
git branch  #(master)
git merge goods_params
git push
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值