三级分类功能 递归树形结构数据获取

三级分类功能 递归树形结构数据获取

1.技术全览

  • 后端采用的技术是SpringBoot+MybatisPlus+Hutool(可选)
  • 前端采用的技术是VUE +ElementUI

2.后端实现

2.1 依赖

<dependency>
   <groupId>cn.hutool</groupId>
   <artifactId>hutool-all</artifactId>
   <version>5.8.3</version>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.2.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
 </dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.8</version>
</dependency>

2.2 application.yml配置文件

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://192.168.14.155:3306/gulimall_pms
    driver-class-name: com.mysql.jdbc.Driver
  application:
    name: gulimall-product
mybatis-plus:
  mapper-locations: classpath*:/mapper/**/*.xml
  global-config:
    db-config:
      id-type: auto 
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
server:
  port: 10000

2.3 实体类

/**
 * 商品三级分类
 */
@Data
@TableName("pms_category")
public class CategoryEntity implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 分类id
     */
    @TableId
    private Long catId;
    /**
     * 分类名称
     */
    private String name;
    /**
     * 父分类id
     */
    private Long parentCid;
    /**
     * 层级
     */
    private Integer catLevel;
    /**
     * 是否显示[0-不显示,1显示]
     */
    private Integer showStatus;
    /**
     * 排序
     */
    private Integer sort;
    /**
     * 图标地址
     */
    private String icon;
    /**
     * 计量单位
     */
    private String productUnit;
    /**
     * 商品数量
     */
    private Integer productCount;

    //添加属性,保存除一级分类以外的其他分类信息,,因该字段未在数据库中,添加plus的 @TableField(exist = false)
    @TableField(exist = false)
    private List<CategoryEntity> children;
}

2.4 DAO层

/**
 * 商品三级分类
 */
@Mapper
public interface CategoryDao extends BaseMapper<CategoryEntity> {}

2.5 service

/**
 * 商品三级分类
 */
public interface CategoryService extends IService<CategoryEntity> {
    List<CategoryEntity> listWithTree();
}

2.6 serviceImpl

@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    /**
     * 可以注入CategoryDao,可以通过  ServiceImpl  查询得 内部以注入一个 M baseMapper;可直接使用
     */
    
    //@Resource
    //private CategoryDao categoryDao;
    
    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2.组装成父子的树形结构
        //2.1首先找到1级分类,1级分类特点:parent_cid为0
        /**
         * .filter(categoryEntity ->categoryEntity.getParentCid() == 0)过滤掉parent_cid不为0
         * .map((t)->{t.}) 将当前菜单的子分类保存,,
         * .sorted((menu1, menu2) -> {return menu1.getSort() - menu2.getSort();} )   重新组装之后进行排序
         * .collect(Collectors.toList())  在重新生成为list
         */
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map(menu -> {
            menu.setChildren(getChildrens(menu, entities));
            return menu;
        }).sorted((category1, category2) -> {
                    return (category1.getSort() == null ? 0 : category1.getSort()) - (category2.getSort() == null ? 0 : category2.getSort());
                }
        ).collect(Collectors.toList());
        return level1Menus;
    }
    /**
     * 递归查找所有菜单的子类
     * 获取当前分类下的所有的子类
     *
     * @param root 当前菜单
     * @param all  所有菜单
     * @return
     */
    public List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> childrens = all.stream().filter(categoryEntity -> {
                    return categoryEntity.getParentCid().equals(root.getCatId());
     }).map((category) -> {
       //找到子菜单 -- 递归
      category.setChildren(getChildrens(category, all));
                    return category;
       })
       .sorted((category1, category2) -> {
        //菜单的排序                
         return (category1.getSort() == null ? 0 : category1.getSort()) - (category2.getSort() == null ? 0 : category2.getSort());
                }).collect(Collectors.toList());

        return childrens;
    }
}

2.7 controller

/**
 * 商品三级分类
 */
@RestController
@RequestMapping("product/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 查出所有的分类,以及子分类,以树形结构组装起来
     */
    @RequestMapping("/list/tree")
    public R list() {
        List<CategoryEntity> entities = categoryService.listWithTree();

        return R.ok().put("data", entities);
    }
    
	/**
     *通过hutool的树结构工具-TreeUtil
     */
    @RequestMapping("/list/tree1")
    public R list1() {
        List<CategoryEntity> nodeList = categoryService.list();
        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        // 最大递归深度
        treeNodeConfig.setDeep(3);
        //转换器
        List<Tree<String>> treeNodes = TreeUtil.build(nodeList,"0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getCatId().toString());
                    tree.setParentId(treeNode.getParentCid().toString());
                    tree.setWeight(treeNode.getSort());
                    tree.setName(treeNode.getName());
                    // 扩展属性 ...
                    tree.putExtra("catId", treeNode.getCatId());
                    tree.putExtra("name", treeNode.getName());
                    tree.putExtra("parentCid", treeNode.getParentCid());
                    tree.putExtra("catLevel", treeNode.getCatLevel());
                    tree.putExtra("showStatus", treeNode.getShowStatus());
                    tree.putExtra("sort", treeNode.getSort());
                    tree.putExtra("icon", treeNode.getIcon());
                    tree.putExtra("productUnit", treeNode.getProductUnit());
                    tree.putExtra("productCount", treeNode.getProductCount());
                });
        return R.ok().put("data", treeNodes);
    }
}

3.前端vue实现

<template>
  <el-tree :data="menus" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
</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;
          console.log("成功获取到数据!", data.data)
        }
      )
    },
  },
  created() {
    this.getMenus();
  }
};
</script>

4.效果展示

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值