1. 程式人生 > 程式設計 >jdk1.8+vue elementui實現多級選單功能

jdk1.8+vue elementui實現多級選單功能

前言:在學習穀粒商城的時候,在做分類維護樹形選單維護的功能中,專案中只講了選單三級樹怎麼實現,想拓展一下多級選單,功能已實現,記錄一下,有不對的地方歡迎指正。

一、後端部分

使用Jdk1.8的新特性Stream和lamada表示式,資料庫的框架使用苞米豆的mybatis plus,話不多說,上程式碼

1. 新建ManyTree類,可封裝成工具類

import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.util.List;
import java.util.Map;
public class ManyTree {

 private List<CategoryEntity> rootList; // 根節點物件存放到這裡
 private List<CategoryEntity> bodyList; // 其他節點存放到這裡,可以包含根節點

 public ManyTree(List<CategoryEntity> rootList,List<CategoryEntity> bodyList) {
  this.rootList = rootList;
  this.bodyList = bodyList;
 }

 public List<CategoryEntity> getTree() { // 呼叫的方法入口
  if (bodyList != null && !bodyList.isEmpty()) {
   // 宣告一個map,用來過濾已操作過的資料
   Map<String,String> map = Maps.newHashMapWithExpectedSize(bodyList.size());
   rootList.forEach(beanTree -> getChild(beanTree,map));
   return rootList;
  }
  return null;
 }

 public void getChild(CategoryEntity beanTree,Map<String,String> map) {
  List<CategoryEntity> childList = Lists.newArrayList();
  bodyList.stream().filter(c -> !map.containsKey(c.getCatId())).filter(c -> c.getParentCid().equals(beanTree.getCatId()))
    .forEach(c -> {
     map.put(String.valueOf(c.getCatId()),String.valueOf(c.getParentCid()));
     getChild(c,map);
     childList.add(c);
    });
  beanTree.setChildren(childList);
 }

}

2. 新建實體CategoryEntity,這裡用了lombok,idea安裝lombok外掛,專案新增lombok的依賴,詳細自行百度

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.List;
import lombok.Data;
/**
 * 商品分類
 * 
 */
@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;
	/**
	 * 層級,1 2 3層
	 */
	private Integer catLevel;
	/**
	 * 展示狀態,可用作邏輯刪除
	 */
	private Integer showStatus;
	/**
	 * 排序欄位
	 */
	private Integer sort;
	/**
	 * 展示圖示
	 */
	private String icon;
	private String productUnit;
	private Integer productCount;
	//這個註解的含義是在資料庫表中不存在
	/**
	 * 用於裝載子選單children
	 */
	@TableField(exist=false)
	private List<CategoryEntity> children;
}

3. 業務層新建service,這裡只貼service實現層的程式碼

 /**
  * 遞迴查詢樹形選單資料邏輯已經抽取出來,
  * 這裡只需要傳入兩個資料集合即可:1、所有選單資料,包括根節點以及子節點 2、所有一級選單資料
  * @return
  */
 @Override
 public List<CategoryEntity> getAllTree() {
  //使用mybatis-plus自帶的baseMapper.selectList方法查詢出所有
  List<CategoryEntity> bodyList = baseMapper.selectList(null);
  //使用xml查詢出所有一級選單
  List<CategoryEntity> rootList = categoryDao.getRootTree();
  ManyTree utils = new ManyTree(rootList,bodyList);
  List<CategoryEntity> result = utils.getTree();
  return result;
 }

二、前端部分

1. Category.vue

<template>
 <div class>
 <el-tree
  :data="menus"
  :props="defaultProps"
  :expand-on-click-node="false"
  node-key="catId"
  ref="menuTree"
  :show-checkbox="showCheckbox"
 >
  <span class="custom-tree-node" slot-scope="{ node,data }">
  <span>{{ node.label }}</span>
  <span>
   <el-button type="text" size="mini" @click="() => append(data)">增加</el-button>
   <el-button type="text" size="mini" @click="() => edit(data)">修改</el-button>
   <el-button
   v-if="node.childNodes.length==0"
   type="text"
   size="mini"
   @click="() => remove(node,data)"
   >刪除</el-button>
  </span>
  </span>
 </el-tree>
 </div>
</template>
<script>
//這裡可以匯入其他檔案(比如:元件,工具js,第三方外掛js,json檔案,圖片檔案等等)
//例如:import 《元件名稱》 from '《元件路徑》';
export default {
 //import引入的元件需要注入到物件中才能使用
 components: {},data() {
 //這裡存放資料
 return {
  //選單欄資料
  menus: [],defaultProps: {
		//與後端實體中封裝的子節點名稱對應
  children: "children",label: "name"
  },showCheckbox:true
 };
 },//監聽屬性 類似於data概念
 computed: {},//監控data中的資料變化
 watch: {},//方法集合
 methods: {
 // 獲取選單資料
 getMenus() {
  this.$http({
  url: this.$http.adornUrl("/product/category/list/tree"),method: "get"
  }).then(({ data }) => {
  //console.log("獲取選單資料的data:" + data.data);
  this.menus = data.data;
  });
 },edit(data){
 },append(data) { 
 },//移除節點方法
 remove(node,data) { 
 }
 },//生命週期 - 建立完成(可以訪問當前this例項)
 created() {
 this.getMenus();
 },//生命週期 - 掛載完成(可以訪問DOM元素)
 mounted() {},beforeCreate() {},//生命週期 - 建立之前
 beforeMount() {},//生命週期 - 掛載之前
 beforeUpdate() {},//生命週期 - 更新之前
 updated() {},//生命週期 - 更新之後
 beforeDestroy() {},//生命週期 - 銷燬之前
 destroyed() {},//生命週期 - 銷燬完成
 activated() {} //如果頁面有keep-alive快取功能,這個函式會觸發
};
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css類
</style>

2. 展示效果

在這裡插入圖片描述

三、資料庫

1. 建表sql

CREATE TABLE `pms_category` (
 `cat_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '分類id',`name` char(50) DEFAULT NULL COMMENT '分類名稱',`parent_cid` bigint(20) DEFAULT NULL COMMENT '父分類id',`cat_level` int(11) DEFAULT NULL COMMENT '層級',`show_status` tinyint(4) DEFAULT NULL COMMENT '是否顯示[0-不顯示,1顯示]',`sort` int(11) DEFAULT NULL COMMENT '排序',`icon` char(255) DEFAULT NULL COMMENT '圖示地址',`product_unit` char(50) DEFAULT NULL COMMENT '計量單位',`product_count` int(11) DEFAULT NULL COMMENT '商品數量',PRIMARY KEY (`cat_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1450 DEFAULT CHARSET=utf8mb4 COMMENT='商品分類';

2. 模擬資料
可以自己造些資料,有需要的資料可以雲盤拿,懶得摘了!
連結: https://pan.baidu.com/s/1Brt8682D3ydvorEWhgEUEA 提取碼: kkjx

到此這篇關於jdk1.8+vue elementui實現多級選單功能的文章就介紹到這了,更多相關vue elementui實現多級選單內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!