【谷粒商城基础篇】商品服务开发:基础概念、三级分类

在这里插入图片描述

谷粒商城笔记合集

分布式基础篇分布式高级篇高可用集群篇
===简介&环境搭建===
项目简介与分布式概念(第一、二章)
基础环境搭建(第三章)
===整合SpringCloud===
整合SpringCloud、SpringCloud alibaba(第四、五章)
===前端知识===
前端开发基础知识(第六章)
===商品服务开发===
商品服务开发:基础概念、三级分类(第七、八章)
商品服务开发:品牌管理(第九章)
商品服务开发:属性分组、平台属性(第十、十一章)
商品服务:商品维护(第十二、十三章)
===仓储服务开发===
仓储服务:仓库维护(第十四章)
基础篇总结(第十五章)

七、基础概念

7.1 接口文档

https://easydoc.xyz/s/78237135/ZUqEdvA4/hKJTcbfd

7.2 三级分类💡

一级分类查出二级分类数据,二级分类中查询出三级分类数据

在这里插入图片描述

数据库设计

在这里插入图片描述

7.3 属性分组💡

7.3.1 SPU&SKU

SPU:Standard Product Unit (标准化产品单元)

是商品信息聚合的最小单位,是一组可复用,易检索的标准化信息的组合,该集合描述了一个产品的特性

SKU: Stock KeepingUnit (库存量单位)

即库存进出计量的基本单元,可以是以件,盒,托盘等为单位。SKU 这是对于大型连锁超市DC(配送中心)物流管理的一个必要的方法。现在已经被引申为产品统一编号的简称,每种产品均对应有唯一的 SKU 号。

  • IPhone14:SPU
  • Xiaomi 13:SPU
  • IPhone14 蓝色 128GB:SKU
  • Xiaomi 13 白色 8GB+128GB:SKU

在这里插入图片描述

7.3.2 基本属性&销售属性

每个分类下的商品共享规格参数,与销售属性。只是有些商品不一定更用这个分类下全部的属性:

  • 属性是以三级分类组织起来的
  • 规格参数中有些是可以提供检索的
  • 规格参数也是基本red属性,他们具有自己的分组
  • 属性的分组也是以三级分类组织起来的
  • 属性名确定的,但是值是每一个商品不同来决定的

基本属性

在这里插入图片描述

销售属性

在这里插入图片描述

7.4 Object 划分

  1. PO (persistant object) 持久化对象

    po 就是对应数据库中某一个表的一条记录,多个记录可以用 PO 的集合,PO 中应该不包含任何对数据库到操作

  2. DO ( Domain Object) 领域对象

    就是从现实世界抽象出来的有形或无形的业务实体

  3. TO (Transfer Object) 数据传输对象

    不同的应用程序之间传输的对象

  4. DTO (Data Transfer Object) 数据传输对象

    这个概念来源于 J2EE 的设计模式,原来的目的是为了 EJB的分布式应用提供粗粒度的数据实体,以减少分布式调用的次数,从而提高分数调用的性能和降低网络负载,但在这里,泛指用于展示层与服务层之间的数据传输对象

  5. VO(value object) 值对象

    通常用于业务层之间的数据传递,和 PO 一样也是仅仅包含数据而已,但应是抽象出的业务对象,可以和表对应,也可以不,这根据业务的需要,用 new 关键字创建,由 GC 回收view Object 试图对象,接受页面传递来的数据,封装对象,封装页面需要用的数据

  6. BO(business object) 业务对象

    从业务模型的角度看,见 UML 原件领域模型中的领域对象,封装业务逻辑的, java 对象,通过调用 DAO 方法,结合 PO VO,进行业务操作,business object 业务对象,主要作用是把业务逻辑封装成一个对象,这个对象包括一个或多个对象,比如一个简历,有教育经历,工作经历,社会关系等等,我们可以把教育经历对应一个 PO 、工作经验对应一个 PO、 社会关系对应一个 PO, 建立一个对应简历的的 BO 对象处理简历,每 个 BO 包含这些 PO ,这样处理业务逻辑时,我们就可以针对 BO 去处理

  7. POJO ( plain ordinary java object) 简单无规则 java 对象

    POJO 是 DO/DTO/BO/VO 的统称

    传统意义的 java 对象,就是说一些 Object/Relation Mapping 工具中,能够做到维护数据库表记录的 persisent object 完全是一个符合 Java Bean 规范的 纯 java 对象,没有增加别的属性和方法,我们的理解就是最基本的 Java bean 只有属性字段 setter 和 getter 方法

  8. DAO(data access object) 数据访问对象

    是一个 sun 的一个标准 j2ee 设计模式,这个模式有个接口就是 DAO ,他负持久层的操作,为业务层提供接口,此对象用于访问数据库,通常和 PO 结合使用,DAO 中包含了各种数据库的操作方法,通过它的方法,结合 PO 对数据库进行相关操作,夹在业务逻辑与数据库资源中间,配合VO 提供数据库的 CRUD 功能

八、商品服务&三级分类

8.1 API:查询所有分类及子分类💡

商品服务bilimall-product

  1. 使用 sql 脚本给表 pms_catelog 插入数据

  2. 编写API:查询所有分类,组装成父子的树形结构的数据

    1. CategoryController

      /**
       * 查询所有分类以及子分类,以树形结构组装起来
       */
      @RequestMapping("/list/tree")
      public R list(){
          List<CategoryEntity> categories=categoryService.listWithTree();
          return R.ok().put("data", categories);
      }
      
    2. CategoryService

      /**
       * 查询所有分类以及子分类,以树形结构组装起来
       * @return
       */
      List<CategoryEntity> listWithTree();
      
    3. CategoryEntity:增加子分类属性

      /**
       * 子分类
       */
      @TableField(exist = false)
      private List<CategoryEntity> children;
      
    4. CategoryServiceImpl

      /**
       * 查询所有分类以及子分类,以树形结构组装起来
       * @return
       */
      @Override
      public List<CategoryEntity> listWithTree() {
          //1.查询所有分类数据
          List<CategoryEntity> entities = baseMapper.selectList(null);
          //2.以树形结构组装分类数据
          List<CategoryEntity> collect = entities.stream().filter(item ->
              //2.1 返回一级分类
              item.getParentCid()==0
          ).map(item->{
              //2.2 递归找出子分类
              item.setChildren(getChildrens(item,entities));
              return item;
          }).sorted((item1,item2)->{
              //3.一级分类排序
              return (item1.getSort() == null ? 0 : item1.getSort())-(item2.getSort() == null ? 0 : item2.getSort());
          }).collect(Collectors.toList());
      
          return collect;
      }
      
      //递归找出当前分类的子分类,并返回当前分类
      private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> data){
          return data.stream().filter(item -> item.getParentCid().equals(root.getCatId())).map(item->{
              item.setChildren(getChildrens(item,data));
              return item;
          }).sorted((item1,item2)->{
              //2.3 子分类排序
              return (item1.getSort() == null ? 0 : item1.getSort())-(item2.getSort() == null ? 0 : item2.getSort());
          }).collect(Collectors.toList());
      }
      

8.2 前后端联调:树形控件💡

8.2.1 前端开发:树形控件

  1. 启动管理系统前后端服务

  2. 在管理系统前端项目 系统管理-菜单管理 中新增:商品系统 目录、分类维护菜单

    在这里插入图片描述

  3. 分析管理系统前端项目的结构以及路由规则:创建 商品系统 的视图文件夹,创建 分类维护 组件并初始化代码结构

    文件夹:views/modules/product、组件:views/modules/product/category.vue

    <template>
      <div class=''>三级分类维护</div>
    </template>
    

    在这里插入图片描述

  4. 在管理系统前端项目 分类维护 中添加element-ui树形控件,并在组件创建完成时请求分类数据

    views/modules/product/category.vue

    <template>
      <div class=''>
        <el-tree :data="menus" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
      </div>
    </template>
    <script>
    export default {
      ...
      data () {
        return {
          menus: [],
          defaultProps: {
            children: 'children',
            label: 'name'
          }
        }
      },
      methods: {
        handleNodeClick (data) {
          console.log(data)
        },
        getMenus () {
          this.$http({
            url: this.$http.adornUrl('/product/category/list/tree'),
            method: 'get'
          }).then(({data}) => {
            this.menus = data.data
          })
        }
      },
      // 生命周期 - 创建完成(可以访问当前 this 实例)
      created () {
        this.getMenus()
      }
    }
    </script>
    

8.2.2 问题产生💡

管理系统前端项目 需要通过网关请求 管理系统后端项目、商品服务等服务 的验证码、三级分类数据等资源,所有使用请求路径区分不同服务的资源并由 网关服务 进行转发

  • 需要修改请求基本api到 bilimall-gateway

    statis/config/index.js

    // api接口请求地址
    window.SITE_CONFIG['baseUrl'] = 'http://localhost:88/api'
    
  • 需要将 管理系统后端项目 注册到nacos中

  • 需要修改 网关服务 的路由规则

8.2.3 后端处理:/api/**

  1. 将 管理系统后端项目 注册到nacos中:在管理系统后端服务 renren-fast 中注入公务服务依赖,降低 SpringBoot 依赖版本,配置 nacos注册与配置中心,在主启动类中开启服务注册发现功能

    pom.xml

    <!-- 降低SpringBoot依赖版本 -->
    <parent>
    	<groupId>org.springframework.boot</groupId>
    	<artifactId>spring-boot-starter-parent</artifactId>
    	<version>2.1.8.RELEASE</version>
    </parent>
    <!-- 公共依赖 -->
    <dependency>
    	<groupId>cn.lzwei.bilimall</groupId>
    	<artifactId>bilimall-common</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    </dependency>
    

    application.yaml

    spring:
      application:
        name: renren-fast
      cloud:
        nacos:
          discovery:
            server-addr: 114.132.162.129:8848
    

    bootstrap.properties

    spring.application.name=renren-fast
    spring.cloud.nacos.config.server-addr=114.132.162.129:8848
    

    RenrenApplication

    @EnableDiscoveryClient
    
  2. 修改 网关服务 的路由规则:在网关服务 bilimall-gateway 中配置 路由规则 并启动网关服务,先让所有前端请求转发到 renren-fast服务

    application.yaml

    spring:
      cloud:
        gateway:
          routes:
            - id: admin_route
              uri: lb://renren-fast
              predicates:
                - Path=/api/**
              filters:
                - RewritePath=/api/?(?<segment>.*),/renren-fast/$\{segment}
    
  3. 产生跨域问题

8.2.4 产生跨域问题💡

相关资料参考:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS

跨域

跨域:指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对javascript施加的安全限制

同源策略:是指协议,域名,端口都要相同,其中有一个不同都会产生跨域;

下图详细说明了 URL 的改变导致是否允许通信

在这里插入图片描述

预检请求

浏览器发送 非简单请求 都要实现 发送一个请求询问是否可以进行通信 ,我直接给你返回可以通信不就可以了吗?

在这里插入图片描述

在这里插入图片描述

8.2.5 跨域处理

1)方法介绍

方法一:使用nginx部署为同一域

请求 nginx,任何由 nginx 转发请求

开发过于麻烦,上线再使用

在这里插入图片描述

方法二:配置当次请求允许跨域

在响应请求时统一添加下列响应头,告诉浏览器可以进行通信

  • Access-Control-Allow-Origin: 支持哪些来源的请求跨域

  • Access-Control-Allow-Methods: 支持哪些方法跨域

  • Access-Control-Allow-Credentials: 跨域请求默认不包含cookie,设置为true可以包含cookie

  • Access-Control-Expose-Headers: 跨域请求暴露的字段

    ​ CORS请求时, XML .HttpRequest对象的getResponseHeader()方法只能拿到6个基本字段: CacheControl、Content-L anguage、Content Type、Expires、

    Last-Modified、 Pragma。 如果想拿到其他字段,就必须在Access-Control-Expose-Headers里面指定。

  • Access-Control-Max- Age: 表明该响应的有效时间为多少秒。在有效时间内,浏览器无须为同一-请求再次发起预检请求。请注意,浏览器自身维护了一个最大有效时间,如果该首部字段的值超过了最大有效时间,将不会生效。

2)问题解决
  1. 网关服务bilimall-gateway 中添加跨域配置类,并在 管理系统后端服务renren-fast 中注释掉单独进行的跨域处理

    package cn.lzwei.bilimall.gateway.config;
    
    @Configuration
    public class BilimallCorsConfiguration {
        @Bean
        public CorsWebFilter corsWebFilter(){
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            // 配置跨越
            CorsConfiguration corsConfiguration = new CorsConfiguration();
            corsConfiguration.addAllowedHeader("*");
            corsConfiguration.addAllowedMethod("*");
            corsConfiguration.addAllowedOrigin("*");
            corsConfiguration.setAllowCredentials(true);
            // 注册跨越配置
            source.registerCorsConfiguration("/**",corsConfiguration);
            return new CorsWebFilter(source);
        }
    }
    
    package io.renren.config;
    
    @Configuration
    public class CorsConfig implements WebMvcConfigurer {
    //    @Override
    //    public void addCorsMappings(CorsRegistry registry) {
    //        registry.addMapping("/**")
    //            .allowedOriginPatterns("*")
    //            .allowCredentials(true)
    //            .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
    //            .maxAge(3600);
    //    }
    }
    
  2. 重启服务,问题解决

    在这里插入图片描述

8.2.6 后端处理:/api/product/**

修改 网关服务bilimall-gateway 的路由规则:让 /api/product/** 的请求转发到 商品服务。注意规则顺序,路径更具体的优先级更高

spring:
  cloud:
    gateway:
      routes:
        - id: product_route
            uri: lb://bilimall-product
            predicates:
              - Path=/api/product/**
            filters:
              - RewritePath=/api/product/?(?<segment>.*),/product/$\{segment}

重启服务,展示效果

在这里插入图片描述

8.3 前端开发:删除、新增按钮

在这里插入图片描述

views/modules/product/category.vue

<template>
  <div class="">
    <el-tree :data="menus" :props="defaultProps" :expand-on-click-node="false" show-checkbox node-key="catId">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button v-if="node.level" type="text" size="mini" @click="() => append(data)"> Append </el-button>
          <el-button v-if="node.childNodes.length==0" type="text" size="mini" @click="() => remove(node, data)"> Delete </el-button>
        </span>
      </span>
    </el-tree>
  </div>
</template>

<script>
export default {
  methods: {
    getMenus () {
      this.$http({
        url: this.$http.adornUrl('/product/category/list/tree'),
        method: 'get'
      }).then(({data}) => {
        this.menus = data.data
      })
    },
    append (data) {
      console.log(data)
    },
    remove (node, data) {
      console.log(node, data)
    }
  }
}
</script>

8.4 API:逻辑删除💡

在这里插入图片描述

商品服务bilimall-product

  1. CategoryController

    /**
     * 逻辑删除分类数据(包括批量删除)
     * @RequestBody 获取请求体的内容,要求发送 POST 请求
     * Spring MVC 会将请求体的内容转换成对应类型
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] catIds){
    	//categoryService.removeByIds(Arrays.asList(catIds)); 注释直接删除
        //逻辑删除分类数据
        categoryService.removeMenuByIds(catIds);
        return R.ok();
    }
    
  2. CategoryService

    /**
     * 逻辑删除分类数据(包括批量删除)
     * @RequestBody 获取请求体的内容,要求发送 POST 请求
     * Spring MVC 会将请求体的内容转换成对应类型
     */
    void removeMenuByIds(Long[] catIds);
    
  3. CategoryServiceImpl

    /**
     * 逻辑删除分类数据(包括批量删除)
     * @RequestBody 获取请求体的内容,要求发送 POST 请求
     * Spring MVC 会将请求体的内容转换成对应类型
     */
    @Override
    public void removeMenuByIds(Long[] catIds) {
        //TODO 检查当前删除的菜单,是否被别的地方引用
        //逻辑删除:配置逻辑
        baseMapper.deleteBatchIds(Arrays.asList(catIds));
    }
    
  4. application.yaml

    mybatis-plus:
      ...
      global-config:
        db-config:
          logic-delete-value: 1 # 逻辑已删除值(默认为 1)
          logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
    
  5. CategoryEntity

    /**
     * 是否显示[0-不显示,1显示]
     */
    @TableLogic(value = "1",delval = "0")
    private Integer showStatus;
    

8.5 前端开发:删除

在这里插入图片描述

views/modules/product/category.vue

<template>
  <div class="">
    <el-tree :data="menus" :props="defaultProps" :expand-on-click-node="false" show-checkbox node-key="catId" :default-expanded-keys="expandedKey">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button v-if="node.level" type="text" size="mini" @click="() => append(data)"> Append </el-button>
          <el-button v-if="node.childNodes.length==0" type="text" size="mini" @click="() => remove(node, data)"> Delete </el-button>
        </span>
      </span>
    </el-tree>
  </div>
</template>

<script>
export default {
  data () {
    return {
      expandedKey: []
    }
  },
  methods: {
    ...,
    remove (node, data) {
      var ids = [data.catId]
      this.$confirm(`是否删除【${data.name}】菜单?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/product/category/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({data}) => {
          this.$message({
            message: '菜单删除成功',
            type: 'success'
          })
          // 刷新菜单
          this.getMenus()
          // 设置默认展开的菜单
          this.expandedKey = [node.parent.data.catId]
        })
      }).catch(() => {})
    }
  }
}
</script>

8.6 API&前端开发:新增、修改💡

8.6.1 效果展示

  • 新增

    在这里插入图片描述

  • 修改

    在这里插入图片描述

8.6.2 细节考虑

  • 添加完成后要把表单的数据进行清除,否则第二次打开任然会有上次表单提交剩下的数据 this.category.name = “”;
  • 修改和新增用的是同一个表单,因此在方法对话框中 动态的绑定了 :title=“title” 标题 用于显示是新增还是修改
  • 一个表单都是一个提交方法 因此在提交方法的时候进行了判断,根据变量赋值决定调用那个方法 this.dialogType = “add”; this.dialogType = “edit”;

8.6.3 开发

API

CategoryController

/**
 * 新增保存
 */
@RequestMapping("/save")
public R save(@RequestBody CategoryEntity category){
	categoryService.save(category);

    return R.ok();
}
/**
 * 修改查询实时信息
 */
@RequestMapping("/info/{catId}")
public R info(@PathVariable("catId") Long catId){
	CategoryEntity category = categoryService.getById(catId);

    return R.ok().put("data", category); //返回数据使用 data 封装
}
/**
 * 修改
 */
@RequestMapping("/update")
public R update(@RequestBody CategoryEntity category){
	categoryService.updateById(category);
    return R.ok();
}

前端

views/modules/product/category.vue

<template>
  <div class="">
    <el-tree :data="menus" :props="defaultProps" :expand-on-click-node="false" show-checkbox node-key="catId" :default-expanded-keys="expandedKey">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button v-if="node.level<3" type="text" size="mini" @click="() => append(data)"> Append </el-button>
          <el-button type="text" size="mini" @click="edit(data)">edit</el-button>
        </span>
      </span>
    </el-tree>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="30%" :close-on-click-modal="false">
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input v-model="category.productUnit" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      title: '',
      dialogType: '', // edit,add
      category: {
        name: '',
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        productUnit: '',
        icon: '',
        catId: null
      },
      dialogVisible: false
    }
  },
  methods: {
    // 点击 edit
    edit (data) {
      console.log('要修改的数据', data)
      this.dialogType = 'edit'
      this.title = '修改分类'
      this.dialogVisible = true

      // 发送请求获取当前节点最新的数据
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: 'get'
      }).then(({ data }) => {
        // 请求成功
        console.log('要回显的数据', data)
        this.category.name = data.data.name
        this.category.catId = data.data.catId
        this.category.icon = data.data.icon
        this.category.productUnit = data.data.productUnit
        this.category.parentCid = data.data.parentCid
        this.category.catLevel = data.data.catLevel
        this.category.sort = data.data.sort
        this.category.showStatus = data.data.showStatus
      })
    },
    // 点击 append
    append (data) {
      console.log('append', data)
      this.dialogType = 'add'
      this.title = '添加分类'
      this.dialogVisible = true
      this.category.parentCid = data.catId
      this.category.catLevel = data.catLevel * 1 + 1
      this.category.catId = null
      this.category.name = ''
      this.category.icon = ''
      this.category.productUnit = ''
      this.category.sort = 0
      this.category.showStatus = 1
    },
    // 点击对话框确定
    submitData () {
      if (this.dialogType === 'add') {
        this.addCategory()
      }
      if (this.dialogType === 'edit') {
        this.editCategory()
      }
    },
    // 提交修改
    editCategory () {
      var { catId, name, icon, productUnit } = this.category
      this.$http({
        url: this.$http.adornUrl('/product/category/update'),
        method: 'post',
        data: this.$http.adornData({ catId, name, icon, productUnit }, false)
      }).then(({ data }) => {
        this.$message({
          message: '菜单修改成功',
          type: 'success'
        })
        // 关闭对话框
        this.dialogVisible = false
        // 刷新出新的菜单
        this.getMenus()
        // 设置需要默认展开的菜单
        this.expandedKey = [this.category.parentCid]
      })
    },
    // 提交新增
    addCategory () {
      console.log('提交的三级分类数据', this.category)
      this.$http({
        url: this.$http.adornUrl('/product/category/save'),
        method: 'post',
        data: this.$http.adornData(this.category, false)
      }).then(({data}) => {
        this.$message({
          message: '菜单保存成功',
          type: 'success'
        })
        // 关闭对话框
        this.dialogVisible = false
          // 刷新菜单
        this.getMenus()
          // 设置默认展开的菜单
        this.expandedKey = [this.category.parentCid]
      })
    }
  }
}
</script>

8.7 API&前端开发:拖拉拽💡

在这里插入图片描述

API

CategoryController

/**
 * 拖拉拽批量修改:parent_cid、cat_level、sort
 */
@RequestMapping("/update/sort")
public R updateSort(@RequestBody CategoryEntity[] category){
    categoryService.updateBatchById(Arrays.asList(category));

    return R.ok();
}

前端

<template>
  <div class="">
    <el-switch v-model="draggable" active-text="开启拖拽" inactive-text="关闭拖拽"></el-switch>
    <el-button v-if="draggable" @click="batchSave">批量保存</el-button>
    <el-tree :data="menus" :props="defaultProps" :expand-on-click-node="false" show-checkbox node-key="catId" :default-expanded-keys="expandedKey" 
    :draggable="draggable" :allow-drop="allowDrop" @node-drop="handleDrop">
    </el-tree>
  </div>
</template>

<script>
export default {
  data () {
    return {
      pCid: [],
      draggable: false,
      updateNodes: [], // 拖拉拽产生的需要修改的节点
      maxLevel: 0
    }
  },
  methods: {
    // 拖拉拽:批量保存
    batchSave () {
      this.$http({
        url: this.$http.adornUrl('/product/category/update/sort'),
        method: 'post',
        data: this.$http.adornData(this.updateNodes, false)
      }).then(({ data }) => {
        this.$message({
          message: '菜单顺序等修改成功',
          type: 'success'
        })
        // 刷新出新的菜单
        this.getMenus()
        // 设置需要默认展开的菜单
        this.expandedKey = this.pCid
        this.updateNodes = []
        this.maxLevel = 0
        // this.pCid = 0;
      })
    },
    // 拖拉拽:处理所有关联节点中 父节点id(parent_cid)、节点层级(cat_level)、节点的顺序(sort) 的变化
    handleDrop (draggingNode, dropNode, dropType, ev) {
      console.log('handleDrop: ', draggingNode, dropNode, dropType)
      // 1、获取拖拽后父节点id,所有关联节点
      let pCid = 0
      let siblings = null
      if (dropType === 'before' || dropType === 'after') {
        pCid = dropNode.parent.data.catId === undefined ? 0 : dropNode.parent.data.catId
        siblings = dropNode.parent.childNodes
      } else {
        pCid = dropNode.data.catId
        siblings = dropNode.childNodes
      }
      this.pCid.push(pCid)

      // 2、遍历所有关联节点:将修改后的节点信息添加到 this.updateNodes 中
      for (let i = 0; i < siblings.length; i++) {
        // 2.1 拖拽节点
        if (siblings[i].data.catId === draggingNode.data.catId) {
          // 1、获取旧层级
          let catLevel = draggingNode.level
          // 2、层级发送变化
          if (siblings[i].level !== draggingNode.level) {
            // 赋值为最新层级
            catLevel = siblings[i].level
            // 修改他子节点的层级
            this.updateChildNodeLevel(siblings[i])
          }
          // 3、添加到 this.updateNodes 中
          this.updateNodes.push({
            catId: siblings[i].data.catId,
            sort: i,
            parentCid: pCid,
            catLevel: catLevel
          })
        } else {
          // 2.2 兄弟节点添加到 this.updateNodes 中:修改节点顺序
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i })
        }
      }
    },
    // 拖拉拽:修改拖拽节点的子节点的层级
    updateChildNodeLevel (node) {
      if (node.childNodes.length > 0) {
        // 遍历子节点
        for (let i = 0; i < node.childNodes.length; i++) {
          var cNode = node.childNodes[i].data
          // 1.子节点添加到 this.updateNodes 中:修改层级
          this.updateNodes.push({
            catId: cNode.catId,
            catLevel: node.childNodes[i].level
          })
          // 2.递归子节点的子节点
          this.updateChildNodeLevel(node.childNodes[i])
        }
      }
    },
    // 拖拉拽:判断是否被允许
    allowDrop (draggingNode, dropNode, type) {
      this.maxLevel = 0
      // 被拖动的当前节点以及所在的父节点总层数不能大于3
      console.log('allowDrop:', draggingNode, dropNode, type)
      // 1、计算子节点的最大层级
      this.countNodeLevel(draggingNode)
      // 2、求出拖拽节点拥有的层级
      let deep = Math.abs(this.maxLevel - draggingNode.level) + 1
      // 3、判断总层级是否<=3
      if (type === 'inner') {
        return deep + dropNode.level <= 3
      } else {
        return deep + dropNode.parent.level <= 3
      }
    },
    // 拖拉拽:子节点的最大层级,用于判断是否被允许拖拉拽
    countNodeLevel (node) {
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          if (node.childNodes[i].level > this.maxLevel) {
            this.maxLevel = node.childNodes[i].level
          }
          this.countNodeLevel(node.childNodes[i])
        }
      } else {
        this.maxLevel = node.level
      }
    }
}
</script>

8.8 前端开发:批量删除

在这里插入图片描述

使用前面的API

CategoryController

/**
 * 逻辑删除分类数据(包括批量删除)
 * @RequestBody 获取请求体的内容,要求发送 POST 请求
 * Spring MVC 会将请求体的内容转换成对应类型
 */
@RequestMapping("/delete")
public R delete(@RequestBody Long[] catIds){
	//categoryService.removeByIds(Arrays.asList(catIds)); 注释直接删除
    //逻辑删除分类数据
    categoryService.removeMenuByIds(catIds);
    return R.ok();
}

前端开发

<template>
  <div class="">
    <el-button type="danger" @click="batchDelete">批量删除</el-button>
    <el-tree :data="menus" :props="defaultProps" :expand-on-click-node="false" show-checkbox node-key="catId" :default-expanded-keys="expandedKey" 
    :draggable="draggable" :allow-drop="allowDrop" @node-drop="handleDrop" ref="menuTree">
    </el-tree>
  </div>
</template>

<script>
export default {
  methods: {
    // 批量删除
    batchDelete () {
      let catIds = []
      let checkedNodes = this.$refs.menuTree.getCheckedNodes()
      console.log('被选中的元素', checkedNodes)
      for (let i = 0; i < checkedNodes.length; i++) {
        catIds.push(checkedNodes[i].catId)
      }
      this.$confirm(`是否批量删除菜单?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl('/product/category/delete'),
            method: 'post',
            data: this.$http.adornData(catIds, false)
          }).then(({ data }) => {
            this.$message({
              message: '菜单批量删除成功',
              type: 'success'
            })
            this.getMenus()
          })
        })
        .catch(() => {})
    }
  }
}
</script>

8.9 API:修改优化&品牌分类关系表💡

在这里插入图片描述

  1. CategoryController:修改分类,还需同步修改品牌分类关系表

    @RestController
    @RequestMapping("product/category")
    public class CategoryController {
        @Autowired
        private CategoryService categoryService;
        /**
         * 分类修改:并更新在其他表中的冗余字段
         */
        @RequestMapping("/update")
        public R update(@RequestBody CategoryEntity category){
            categoryService.updateCascade(category);
    
            return R.ok();
        }
    }
    
  2. CategoryService:修改分类,还需同步修改品牌分类关系表

    public interface CategoryService extends IService<CategoryEntity> {
        /**
         * 分类修改:并更新在其他表中的冗余字段
         */
        void updateCascade(CategoryEntity category);
    }
    
  3. CategoryServiceImpl:修改分类,还需同步修改品牌分类关系表

    @Service("categoryService")
    public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
        @Resource
        CategoryBrandRelationService categoryBrandRelationService;
        
        /**
         * 分类修改:并更新在其他表中的冗余字段
         */
        @Transactional
        @Override
        public void updateCascade(CategoryEntity category) {
            this.updateById(category);
            //1.更新 品牌分类关联表
            Long catId = category.getCatId();
            String name = category.getName();
            categoryBrandRelationService.updateCategory(catId,name);
            //TODO 分类修改:更新在其他表中的冗余字段
        }
    }
    
  4. CategoryBrandRelationService:修改分类,还需同步修改品牌分类关系表

    public interface CategoryBrandRelationService extends IService<CategoryBrandRelationEntity> {
        /**
         * 分类修改:并更新在其他表中的冗余字段
         */
        void updateCategory(Long catId, String name);
    }
    
  5. CategoryBrandRelationServiceImpl:修改分类,还需同步修改品牌分类关系表

    @Service("categoryBrandRelationService")
    public class CategoryBrandRelationServiceImpl extends ServiceImpl<CategoryBrandRelationDao, CategoryBrandRelationEntity> implements CategoryBrandRelationService {
        /**
         * 分类修改:并更新在其他表中的冗余字段
         */
        @Override
        public void updateCategory(Long catId, String name) {
            this.baseMapper.updateCategory(catId,name);
        }
    }
    
  6. CategoryBrandRelationDao:修改分类,还需同步修改品牌分类关系表

    @Mapper
    public interface CategoryBrandRelationDao extends BaseMapper<CategoryBrandRelationEntity> {
    
        void updateCategory(@Param("catId") Long catId, @Param("name") String name);
    }
    
  7. CategoryBrandRelationDao.xml:修改分类,还需同步修改品牌分类关系表

    <mapper namespace="cn.lzwei.bilimall.product.dao.CategoryBrandRelationDao">
        <update id="updateCategory">
            UPDATE `pms_category_brand_relation` SET catelog_name=#{name} WHERE catelog_id=#{catId}
        </update>
    </mapper>
    
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

愿你满腹经纶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值