目录

前言:

二. element ui

 2.1官网提供的核心代码

三.表结构

编辑 

四.后端

4.1功能分析

4.2实体类

4.3 查询全部权限显示的结果

4.2修改角色权限的后台方法 

 五.vue

5.0代码总览

5.1树形图

 5.2所需要的绑定数据

5.3所需方法

前言:

先上图看效果,页面不是很美观

elementUI 树形递归查询 elementui树状图_elementUI 树形递归查询

elementUI 树形递归查询 elementui树状图_java_02

二. element ui

elementUI 树形递归查询 elementui树状图_vue.js_03

 2.1官网提供的核心代码

<el-tree
  :data="data"
  show-checkbox
  default-expand-all
  node-key="id"
  ref="tree"
  highlight-current
  :props="defaultProps">
</el-tree>

<div class="buttons">
  <el-button @click="getCheckedNodes">通过 node 获取</el-button>
  <el-button @click="getCheckedKeys">通过 key 获取</el-button>
  <el-button @click="setCheckedNodes">通过 node 设置</el-button>
  <el-button @click="setCheckedKeys">通过 key 设置</el-button>
  <el-button @click="resetChecked">清空</el-button>
</div>

<script>
  export default {
    methods: {
      getCheckedNodes() {
        console.log(this.$refs.tree.getCheckedNodes());
      },
      getCheckedKeys() {
        console.log(this.$refs.tree.getCheckedKeys());
      },
      setCheckedNodes() {
        this.$refs.tree.setCheckedNodes([{
          id: 5,
          label: '二级 2-1'
        }, {
          id: 9,
          label: '三级 1-1-1'
        }]);
      },
      setCheckedKeys() {
        this.$refs.tree.setCheckedKeys([3]);
      },
      resetChecked() {
        this.$refs.tree.setCheckedKeys([]);
      }
    },

    data() {
      return {
        data: [{
          id: 1,
          label: '一级 1',
          children: [{
            id: 4,
            label: '二级 1-1',
            children: [{
              id: 9,
              label: '三级 1-1-1'
            }, {
              id: 10,
              label: '三级 1-1-2'
            }]
          }]
        }, {
          id: 2,
          label: '一级 2',
          children: [{
            id: 5,
            label: '二级 2-1'
          }, {
            id: 6,
            label: '二级 2-2'
          }]
        }, {
          id: 3,
          label: '一级 3',
          children: [{
            id: 7,
            label: '二级 3-1'
          }, {
            id: 8,
            label: '二级 3-2'
          }]
        }],
        defaultProps: {
          children: 'children',
          label: 'label'
        }
      };
    }
  };
</script>

 打开官网找到Tree树形控件,第一次应该很难看懂,我来详细跟大家讲解一下

1.

<el-tree
   :data="data"
   show-checkbox
   default-expand-all
   node-key="id"
   ref="tree"
   highlight-current
   :props="defaultProps">
 </el-tree>
:data="data" 绑定的数据叫data,data可以替换成自己写的集合 
node-key里的id对应的是数据库中表的id  
  ref="tree" 表示这个树形图。
:props="defaultProps"  用来设置树形图的属性 说白了 就是设置节点叫啥,子节点是什么集合。估计还是很懵,到时候直接带大家看项目

2.

getCheckedNodes() {
         console.log(this.$refs.tree.getCheckedNodes());
       },


将勾选的节点以json集合的形式打印到控制台

getCheckedKeys() {
         console.log(this.$refs.tree.getCheckedKeys());
       },

将勾选中的节点以字符串数组的形式打印到控制台

elementUI 树形递归查询 elementui树状图_二级_04

3.

setCheckedKeys() {
         this.$refs.tree.setCheckedKeys([3]);
       },

设置选中的节点的key值,将其样式改为勾选。 里面填的是3,就是把id为3的节点设置为选中状态

setCheckedNodes() {
         this.$refs.tree.setCheckedNodes([{
           id: 5,
           label: '二级 2-1'
         }, {
           id: 9,
           label: '三级 1-1-1'
         }]);
       },

通过json的集合类型来设置选中的节点

4. 

data: [{
           id: 1,
           label: '一级 1',
           children: [{
             id: 4,
             label: '二级 1-1',
             children: [{
               id: 9,
               label: '三级 1-1-1'
             }, {
               id: 10,
               label: '三级 1-1-2'
             }]
           }]
         }, {
           id: 2,
           label: '一级 2',
           children: [{
             id: 5,
             label: '二级 2-1'
           }, {
             id: 6,
             label: '二级 2-2'
           }]
         }, {
           id: 3,
           label: '一级 3',
           children: [{
             id: 7,
             label: '二级 3-1'
           }, {
             id: 8,
             label: '二级 3-2'
           }]
         }],

该示例 树形图绑定的数据类型为data,data数据内部细节为父子孙结构,按照该结构显示到前端页面上。树形图的显示是由绑定的数据结构来决定的。

三.表结构

四.后端

4.1功能分析

1.查询所有的权限,将含有所有权限的集合跟树形图绑定

2.查询不同的角色所拥有的不同权限,用集合存储并调用setCheckedNodes()用来设置选中的节点 

3.修改节点功能

删除该角色所拥有的权限

添加该角色的权限

前端勾选节点,将已勾选的节点的id,打包成string数组,转换成字符串,传给服务器。服务器通过对象的属性保存分割后的字符串id。

4.2实体类

package com.dmdd.javasecuritypractice.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 * 
 * </p>
 *
 * @author xray
 * @since 2023-01-31
 */
@Data
public class Permission implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    private String name;

    private String description;

    private String url;

    private Integer pid;

    private String icon;

    private Integer sort;
    //子权限集合
    @TableField(exist = false)
    private List<Permission> subPermissions;

    @Override
    public String toString() {
        return "Permission{" +
            "id=" + id +
            ", name=" + name +
            ", description=" + description +
            ", url=" + url +
            ", pid=" + pid +
            ", icon=" + icon +
            ", sort=" + sort +
        "}";
    }
}

elementUI 树形递归查询 elementui树状图_java_05

通过一级权限查询二级权限,实体类里面定义一个集合用来存储二级权限 

4.3 查询全部权限显示的结果

elementUI 树形递归查询 elementui树状图_二级_06

包含所有权限的集合的数据形式 ,将该集合传给前端,树形控件绑定该集合,就会以该方式显示到页面上。

4.2修改角色权限的后台方法 

//1,2,3,4,5 中间表的 permission_id permission的 id
    @Transactional
    @Override
    public void setRolePermissions(Long roleId, String permissions) {
        ArrayList<RolePermission> rolePermissions = new ArrayList<>();
        //清空该角色权限
//        boolean b = this.removeById(roleId);
        boolean b = this.remove(new QueryWrapper<RolePermission>().lambda().eq(RolePermission::getRoleId, roleId));
        if (b) {
            //将权限依次赋值给rolePermission
            String[] strings = permissions.split(",");
            for (String permissionId : strings) {
                RolePermission rolePermission = new RolePermission();
                //设置当前角色id 权限id id会自增
                rolePermission.setRoleId(roleId);
                rolePermission.setPermissionId(Long.valueOf(permissionId));
                rolePermissions.add(rolePermission);
            }
            //mybats-plus批量添加方法
            boolean b1 = this.saveBatch(rolePermissions);

        }
    }

对中间表进行操作,实现角色权限的修改 

 五.vue

5.0代码总览

<template>
  <div>
<!--    添加角色的树形结构-->
    <!--权限树对话框-->
    <el-dialog title="权限信息" :visible.sync="dialogTreeVisible">
      <el-tree
          :data="allPermissions"
          show-checkbox
          default-expand-all
          node-key="id"
          ref="tree"
          highlight-current
          :props="defaultProps">
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTreeVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRolePermissions()">确 定</el-button>
      </div>
    </el-dialog>


    <el-button type="text" @click="dialogFormVisible= true">新增模块</el-button>
    <el-dialog title="权限操作" :visible.sync="dialogFormVisible">
      <el-form :model="role">
        <el-form-item label="编号" :label-width="formLabelWidth">
          <el-input v-model="role.id" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="role.name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="描述" :label-width="formLabelWidth">
          <el-input v-model="role.description" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="地区id" :label-width="formLabelWidth">
          <el-input v-model="role.siteId" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="update()">确 定</el-button>
      </div>
    </el-dialog>
    <el-table
        :data="roles"
        style="width: 100%">
      <el-table-column
          label="id"
          width="180">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column
          label="用户名"
          width="180">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <p>姓名: {{ scope.row.name }}</p>
            <p>id: {{ scope.row.id }}</p>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">{{ scope.row.name }}</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
          label="描述"
          width="180">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{ scope.row.description }}</span>
        </template>
      </el-table-column>
      <el-table-column
          label="siteId"
          width="180">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{ scope.row.siteId }}</span>
        </template>
      </el-table-column>



      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">编辑
          </el-button>
          <el-button
              size="mini"
              @click="openTree(scope.row.id)">修改权限
          </el-button>
          <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    //分页功能
    <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        @current-change="loadRole"
    >
    </el-pagination>
  </div>
</template>

<script>
export default {
  name: "RoleView",
  data() {
    return {
      roles: [],
      role: {},
      current: 1,
      total: 0,
      pageSize: 10,
      dialogFormVisible: false,
      formLabelWidth: "120px",
      dialogTreeVisible: false,
      allPermissions: [],
      rolePermissions:[],
      defaultProps: {
        children: 'subPermissions',
        label: 'name'
      },
      RoleId:-1
    }
  },
  methods:{
    //点击修改角色权限 弹出树形图
    openTree(roleId){
      this.RoleId=roleId;
      this.dialogTreeVisible=true
      //查询所有权限通过角色
      this.axios.get("http://localhost:8080/permissionsByRole")
      .then(result=>{
        console.log("所有权限:"+result)
        if (result.data.status=="OK"){
          this.allPermissions=result.data.data;
          //查询该角色拥有的权限
          this.axios.get("http://localhost:8080/permissionsByRoleId?RoleId="+roleId)
          .then(result=>{
            console.log("当前角色的权限"+result)
            if (result.data.status=="OK"){
              this.rolePermissions=result.data.data;
              //设置勾选效果
              this.$refs.tree.setCheckedNodes(this.rolePermissions);
            }
          })
        }
      })
    },
    //设置角色权限
    setRolePermissions(){
      console.log(this.$refs.tree.getCheckedKeys());
      //将数组转换成字符串
      let keys = this.$refs.tree.getCheckedKeys();
      let keyStr=""
      for (let i=0;i<keys.length;i++){
        keyStr+=keys[i]+",";
      }
      keyStr.substr(0,keyStr.length-1);
      //调用后台接口
      this.axios.post("http://localhost:8080/permission/set-role","roleId="+this.RoleId+"&permissions="+keyStr)
      .then(result=>{
        if (result.data.status=="OK"){
          this.$message(result.data.data);
        }
      })
      this.dialogTreeVisible=false;
    },

    //查询角色表
    loadRole(current,pageSize){
      this.current=current;
      this.axios.get("http://localhost:8080/role/page?current="+this.current+"&pageSize="+this.pageSize)
      .then(result=>{
        console.log(result)
        this.roles=result.data.data.records
        this.total=result.data.data.total
      })
    },
    update() {
      if (this.role.id) {
        //执行修改方法
        this.axios.put("http://localhost:8080/role", this.role)
            .then(result => {
              if (result.data.status == "OK") {
                console.log(result.data)
                this.role={}
                this.dialogFormVisible=false
                this.loadRole(this.current)
              }
            })
      }
      else{
        this.axios.post("http://localhost:8080/role",this.role)
            .then(result=>{
              if (result.data.status=="OK"){
                console.log(result)
                this.role={}
                this.dialogFormVisible=false
                this.loadRole(1)
              }
            })
      }
    },
    //回显
    handleEdit(index,row){
      this.role=JSON.parse(JSON.stringify(row));
      this.dialogFormVisible=true
    },
  },
  mounted() {
    this.loadRole(1)
  }
}
</script>

<style scoped>

</style>

5.1树形图

<!--    添加角色的树形结构-->
    <!--权限树对话框-->
    <el-dialog title="权限信息" :visible.sync="dialogTreeVisible">
      <el-tree
          :data="allPermissions"
          show-checkbox
          default-expand-all
          node-key="id"
          ref="tree"
          highlight-current
          :props="defaultProps">
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTreeVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRolePermissions()">确 定</el-button>
      </div>
    </el-dialog>

树形图控件 

 5.2所需要的绑定数据

allPermissions: [],
      rolePermissions:[],
      defaultProps: {
        children: 'subPermissions',
        label: 'name'
      },
      RoleId:-1
defaultProps: {
         children: 'subPermissions',
         label: 'name'
       },

设置树形图父节点下的子集合名字为subPermissions.children属性对应的是父集合下的子集合  

label 表示每个节点的名字 我设置的name表示的是 allPermissions里的对象的name属性值

5.3所需方法

//点击修改角色权限 弹出树形图
    openTree(userId) {
      this.userId = userId;
      this.dialogTreeVisible = true
      //查询所有权限通过角色
      this.axios.get("http://localhost:8080/selectAllRole")
          .then(result => {
            console.log("所有权限:" + result)
            if (result.data.status == "OK") {
              this.allRoles = result.data.data;
              //查询该角色拥有的权限
              this.axios.get("http://localhost:8080/select-role?userId=" + userId)
                  .then(result => {
                    console.log("当前角色的权限" + result)
                    if (result.data.status == "OK") {
                      this.userRoles = result.data.data;
                      //设置勾选效果
                      this.$refs.tree.setCheckedNodes(this.userRoles);
                    }
                  })
            }
          })
    },
    //设置用户的角色
    setUserRoles() {
      console.log(this.$refs.tree.getCheckedKeys());
      //将数组转换成字符串
      let keys = this.$refs.tree.getCheckedKeys();
      let keyStr = ""
      for (let i = 0; i < keys.length; i++) {
        keyStr += keys[i] + ",";
      }
      keyStr.substr(0, keyStr.length - 1);
      //调用后台接口
      this.axios.post("http://localhost:8080/setRole", "userId=" + this.userId + "&roles=" + keyStr)
          .then(result => {
            // if (result.request.status == 200) {
              this.$message(result.data);
            // }
          })
      this.dialogTreeVisible = false;
    },

点击修改权限的按钮,设置树形图为可见,显示所有节点数据,设置勾选节点是哪些。

1.将后端的通过角色查询到的权限的集合传入前台,通过

this.$refs.tree.setCheckedNodes(this.rolePermissions); 设置勾选节点

其他的大家可以自己去体会,如果完全了解的话,不管是怎么样的数据结构的树形图都会写

最后附上我的另一个通过用户查询角色权限的实现图。

elementUI 树形递归查询 elementui树状图_java_07