Elementui Tree 树形控件删除子节点

简介: Elementui Tree 树形控件删除子节点

要求:

Elementui Tree 树形控件,将勾选选中的值放在list集合里面提交

提交格式是这样的,也就是将勾选项放在一个数组里面,作为参数提交给后端即可。

步骤:

这里我用到了json本地的数据,因为掉接口数据,不太方便写demo,后面统一都用到mock,json数据了,如果需要用到项目里面,后面直接修改一下

//获取树权限节点接口定义
    getZtreeList() {
      this.dataLoading = true;
      import("./mock").then((res) => {
        this.setTree = res.data;
        this.organList = res.data.map((a) => ({
          label: a.description,
          value: a.id,
        }));
        this.getListData();
        this.dataLoading = false;
      });
    },

改成这样即可

//调用接口
import {getZtreeList} from "@/api/permission/role";
//获取树权限节点接口定义
    getZtreeList() {
      this.dataLoading = true;
      getZtreeList(params).then((res) => {
        this.setTree = res.data; 
         this.organList = res.data.map((a) => ({
          label: a.description,
          value: a.id,
        }));
        this.getListData();
        this.dataLoading = false;
      });
    },

话不多说了,来看具体的操作吧

1:在views底下新建一个test文件夹

里面新建一个vue文件和一个json文件

2:使用

mock.json

{
    "msg": "success",
    "code": 1,
    "data": [
        {
            "id": 2,
            "permissionToken": "data_spectaculars_token1",
            "description": "数据看板",
            "parentId": 1,
            "checked": true
        },
        {
            "id": 3,
            "permissionToken": "data_spectaculars_stat_token2",
            "description": "统计看板",
            "parentId": 2,
            "checked": true
        },
        {
            "id": 4,
            "permissionToken": "data_spectaculars_health_token2",
            "description": "健康看板",
            "parentId": 2,
            "checked": true
        },
        {
            "id": 1,
            "permissionToken": "system_token0",
            "description": "系统权限",
            "parentId": 0,
            "checked": false
        },
        {
            "id": 5,
            "permissionToken": "account_management_token1",
            "description": "账户管理",
            "parentId": 1,
            "checked": false
        },
        {
            "id": 6,
            "permissionToken": "account_management_user_token2",
            "description": "用户管理",
            "parentId": 5,
            "checked": false
        },
        {
            "id": 7,
            "permissionToken": "account_management_permission_token2",
            "description": "权限管理",
            "parentId": 5,
            "checked": false
        },
        {
            "id": 8,
            "permissionToken": "data_management_token1",
            "description": "数据管理",
            "parentId": 1,
            "checked": false
        },
        {
            "id": 9,
            "permissionToken": "data_management_organ_token2",
            "description": "部门管理",
            "parentId": 8,
            "checked": false
        },
        {
            "id": 10,
            "permissionToken": "data_management_config_token2",
            "description": "数据配置",
            "parentId": 8,
            "checked": false
        },
        {
            "id": 11,
            "permissionToken": "data_management_staff_token2",
            "description": "人员管理",
            "parentId": 8,
            "checked": false
        },
        {
            "id": 12,
            "permissionToken": "data_management_asset_token2",
            "description": "资产管理",
            "parentId": 8,
            "checked": false
        },
        {
            "id": 13,
            "permissionToken": "device_management_token1",
            "description": "设备管理",
            "parentId": 1,
            "checked": false
        }
    ]
}

3:test.vue实例代码

<template>
  <div class="ztree">
    <el-tree
      :data="treeData"
      show-checkbox
      default-expand-all
      node-key="id"
      ref="tree"
      highlight-current
      :props="defaultProps"
      @check="checkHandler"
    >
    </el-tree>
    <el-button type="primary" @click="createData()">确定</el-button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      setTree: [],
      defaultProps: {
        children: "children",
        label: "description",
      },
      treeData: [],
      organList: [],
      questionForm: {
        //permissionTokens: [],
      },
    };
  },
  watch: {},
  created() {
    //加载树节点
    this.getZtreeList();
  },
  methods: {
    //树文件勾选事件
    checkHandler(...value) {
      let a = value[1].checkedNodes.map((a) => a.description);
      let b = value[1].checkedNodes.map((a) => a.permissionToken);
      console.log(a);
      this.questionForm.description = a;
      this.questionForm.permissionToken = b;
    },
    //获取树权限节点接口定义
    getZtreeList() {
      this.dataLoading = true;
      import("./mock").then((res) => {
        this.setTree = res.data;
        this.organList = res.data.map((a) => ({
          label: a.description,
          value: a.id,
        }));
        this.getListData();
        this.dataLoading = false;
      });
    },
    //对json的格式的转化
    getListData() {
      let dataArray = [];
      this.setTree.forEach(function (data) {
        let parentId = data.parentId;
        if (parentId === 0) {
          let objTemp = {
            id: data.id,
            description: data.description,
            permissionToken: data.permissionToken,
            parentId: parentId,
          };
          dataArray.push(objTemp);
        }
      });
      this.treeData = this.data2treeDG(this.setTree, dataArray);
    },
    data2treeDG(datas, dataArray) {
      for (let j = 0; j < dataArray.length; j++) {
        let dataArrayIndex = dataArray[j];
        let childrenArray = [];
        let Id = dataArrayIndex.id;
        for (let i = 0; i < datas.length; i++) {
          let data = datas[i];
          let parentId = data.parentId;
          if (parentId == Id) {
            //判断是否为儿子节点
            let objTemp = {
              id: data.id,
              description: data.description,
              permissionToken: data.permissionToken,
              parentId: parentId,
            };
            childrenArray.push(objTemp);
          }
        }
        dataArrayIndex.children = childrenArray;
        //console.log("打印childrenArray", dataArrayIndex.children);
        if (childrenArray.length > 0) {
          //有儿子节点则递归
          this.data2treeDG(datas, childrenArray);
        }
      }
      // console.log("打印处理过的json", dataArray);
      return dataArray;
    },
    //添加角色
    async createData() {
      const params = this.questionForm;
      alert(JSON.stringify(params));
    },
  },
};
</script>

效果:

以上就是Elementui Tree 树形控件,将勾选选中的值放在list集合里面提交

======================================================

回到今天的正题:

Elementui Tree 树形控件删除子节点功能的实现

在这个功能上

需要接续开发一个功能,前面其实也写过

现在再写一遍

写具体一点吧

(Elementui Tree 树形控件删除子节点)


无论啥时候,写什么代码,都要先看一下文档,毕竟看完文档之后,可以解决99%的问题哦

文档链接:

组件:https://element.eleme.cn/#/zh-CN/component/tree


功能:当鼠标划过Tree 树形控件的节点的时候,会出现一个删除的按钮

点击删除按钮,会出现弹框询问是否删除

选中删除,则删除树节点(最上层的父节点不可删除)


1:第一步,当然是添加删除元素了


在文档里面有这样的说明:

可以通过两种方法进行树节点内容的自定义:render-content和 scoped slot。使用render-content指定渲染函数,该函数返回需要的节点区内容即可。渲染函数的用法请参考 Vue 文档。使用 scoped slot 会传入两个参数node和data,分别表示当前节点的 Node 对象和当前节点的数据。注意:由于 jsfiddle 不支持 JSX 语法,所以render-content示例在 jsfiddle 中无法运行。但是在实际的项目中,只要正确地配置了相关依赖,就可以正常运行。


所以

我们今天使用的还是

:render-content="renderContent"


直接将文档里面的这个例子,赋值到我们的项目代码里面吧,直接简单且粗暴。

renderContent(h, { node, data, store }) {
      console.log(data);
      return (
        <span
          class="custom-tree-node"
          on-mouseenter={() => (data.isHover = true)}
          on-mouseleave={() => (data.isHover = false)}
        >
          <span>{data.description}</span>
          {data.parentId !== 0 && data.isHover && (
            <i
              class="el-icon-error danger"
              on-click={(e) => {
                e.stopPropagation();
                this.remove(node, data);
              }}
            ></i>
          )}
        </span>
      );
    },
    remove(node, data) {
      this.$confirm("此操作将永久删除该条目, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.handleDelete(null, data);
          if (data.parentId === 0) {
            return;
          }
          const parent = node.parent;
          const children = parent.data.children || parent.data;
          const index = children.findIndex((d) => d.id === data.id);
          children.splice(index, 1);
          // 发请求删除
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
     //调用删除接口
    handleDelete(index, row) {
      const params = {
        id: row.id,
      };
      this.dataLoading = true;
      deleteSubject(params).then((res) => {
        this.$notify({
          message: "删除成功",
          type: "success",
          duration: 2000,
        });
        this.getQuerycheckList();
        console.log(this.pvData);
        this.dataLoading = false;
      });
    },

需要注意的地方

因为功能是,当鼠标划过树形控件的子节点的时候

才会出现了那个删除的图标

需要在渲染的时候设置一下isHover: false

isHover: false,

test.vue

<template>
  <div class="ztree">
    <el-tree
      :data="treeData"
      show-checkbox
      default-expand-all
      node-key="id"
      ref="tree"
      highlight-current
      :props="defaultProps"
      @check="checkHandler" 
      :render-content="renderContent"
    >
    </el-tree>
    <el-button type="primary" @click="createData()">确定</el-button>
  </div>
</template>
<script>
//调用接口
// import {
//   deleteSubject,
// } from "@/api/data/organ";
export default {
  data() {
    return {
      setTree: [],
      defaultProps: {
        children: "children",
        label: "description",
      },
      treeData: [],
      organList: [],
      questionForm: {
        //permissionTokens: [],
      },
    };
  },
  created() {
    //加载树节点
    this.getZtreeList();
  },
  methods: {
     renderContent(h, { node, data, store }) {
      console.log(data);
      return (
        <span
          class="custom-tree-node"
          on-mouseenter={() => (data.isHover = true)}
          on-mouseleave={() => (data.isHover = false)}
        >
          <span>{data.description}</span>
          {data.parentId !== 0 && data.isHover && (
            <i
              class="el-icon-error danger"
              on-click={(e) => {
                e.stopPropagation();
                this.remove(node, data);
              }}
            ></i>
          )}
        </span>
      );
    },
    remove(node, data) {
      this.$confirm("此操作将永久删除该条目, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.handleDelete(null, data);
          if (data.parentId === 0) {
            return;
          }
          const parent = node.parent;
          const children = parent.data.children || parent.data;
          const index = children.findIndex((d) => d.id === data.id);
          children.splice(index, 1);
          // 发请求删除
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
     //调用删除接口
    handleDelete(index, row) {
      const params = {
        id: row.id,
      };
      this.dataLoading = true;
      deleteSubject(params).then((res) => {
        this.$notify({
          message: "删除成功",
          type: "success",
          duration: 2000,
        });
        this.getQuerycheckList();
        console.log(this.pvData);
        this.dataLoading = false;
      });
    },
//  nodeClickHandler(...rest) {
//       console.log(rest);
//       this.form = rest[0];
//     },
    //树文件勾选事件
    checkHandler(...value) {
      let a = value[1].checkedNodes.map((a) => a.description);
      let b = value[1].checkedNodes.map((a) => a.permissionToken);
      console.log(a);
      this.questionForm.description = a;
      this.questionForm.permissionToken = b;
    },
    //获取树权限节点接口定义
    getZtreeList() {
      this.dataLoading = true;
      import("./mock").then((res) => {
        this.setTree = res.data;
        this.organList = res.data.map((a) => ({
          label: a.description,
          value: a.id,
        }));
        this.getListData();
        this.dataLoading = false;
      });
    },
    //对json的格式的转化
    getListData() {
      let dataArray = [];
      this.setTree.forEach(function (data) {
        let parentId = data.parentId;
        if (parentId === 0) {
          let objTemp = {
            id: data.id,
            description: data.description,
            permissionToken: data.permissionToken,
            parentId: parentId,
          };
          dataArray.push(objTemp);
        }
      });
      this.treeData = this.data2treeDG(this.setTree, dataArray);
    },
    data2treeDG(datas, dataArray) {
      for (let j = 0; j < dataArray.length; j++) {
        let dataArrayIndex = dataArray[j];
        let childrenArray = [];
        let Id = dataArrayIndex.id;
        for (let i = 0; i < datas.length; i++) {
          let data = datas[i];
          let parentId = data.parentId;
          if (parentId == Id) {
            //判断是否为儿子节点
            let objTemp = {
              id: data.id,
              description: data.description,
              permissionToken: data.permissionToken,
              parentId: parentId,
              isHover: false,
            };
            childrenArray.push(objTemp);
          }
        }
        dataArrayIndex.children = childrenArray;
        //console.log("打印childrenArray", dataArrayIndex.children);
        if (childrenArray.length > 0) {
          //有儿子节点则递归
          this.data2treeDG(datas, childrenArray);
        }
      }
      // console.log("打印处理过的json", dataArray);
      return dataArray;
    },
    //添加角色
    async createData() {
      const params = this.questionForm;
      alert(JSON.stringify(params));
    },
  },
};
</script>
<style lang="scss">
.danger {
  color: red;
}
</style>

效果

删除设备管理的节点,并且想后端发送删除节点的请求,调用接口成功,则删除成功哦。

调用后端接口不成功,则显示取消删除。

相关文章
easyui的tree节点的获取和选中
easyui的tree节点的获取和选中
232 0
|
JSON 前端开发 JavaScript
07zTree - 显示自定义字体的树
07zTree - 显示自定义字体的树
68 0
|
JSON JavaScript 前端开发
vue如何获取Elementui Tree 树形控件当前选中的节点
vue如何获取Elementui Tree 树形控件当前选中的节点
149 0
|
4月前
|
前端开发 虚拟化
简单记录使用 ElementPlus 的虚拟化树形控件(el-tree-v2)心得
这篇文章分享了作者使用ElementPlus的虚拟化树形控件`el-tree-v2`的心得,展示了其基本用法和如何通过自定义模板来增强树节点的交互性。
1550 1
简单记录使用 ElementPlus 的虚拟化树形控件(el-tree-v2)心得
|
5月前
Element UI 树形控件Tree 【详解】el-tree 展开指定节点,判断是否存在指定节点
Element UI 树形控件Tree 【详解】el-tree 展开指定节点,判断是否存在指定节点
921 0
|
6月前
|
存储 前端开发 JavaScript
elementUI Tree 树形控件单选实现
【6月更文挑战第3天】Element UI 的树形控件(el-tree)默认不支持单选,但可以通过监听节点点击事件并手动更新选中状态实现。以下是一个简单的示例,展示如何创建单选树: ```html &
286 0
element组件里的tree树形控件的使用?
element组件里的tree树形控件的使用?
|
7月前
element plus 可选择树形组件(el-tree) 怎样一键展开/收起?实现方法详解
element plus 可选择树形组件(el-tree) 怎样一键展开/收起?实现方法详解
869 2
element plus 可选择树形组件(el-tree) 怎样一键展开/收起?实现方法详解
|
JSON JavaScript 前端开发
Elementui Tree 树形控件删除功能
Elementui Tree 树形控件删除功能
122 0
Elementui Tree 树形控件删除功能
|
7月前
el-tree饿了么elementUI tree树结构插件设置全部展开折叠
el-tree饿了么elementUI tree树结构插件设置全部展开折叠

热门文章

最新文章