美文网首页
Element-ui中tree设置为单选及添加/修改/删除树

Element-ui中tree设置为单选及添加/修改/删除树

作者: leesession | 来源:发表于2019-04-12 14:48 被阅读0次

    1、首先创建树,配置下树的参数

      <el-tree
            :data="data"
            :props="props"
            node-key="uuid"
            :check-strictly="true"
            show-checkbox
            @check-change="checkChange"
            ref="tree">
      </el-tree>
    

    2.data中设置一些值

       data: [],
       props: {
         label: 'name',
         children: 'childList'
       },
      selectOrg: {
         orgJsn:{},//存唯一的值,勾选的
         orgsid: [],//存uuid,与node-key相结合
       }
    

    3.设置方法:

    checkChange(data, checked){
            // 获取当前选择的id在数组中的索引
            const indexs = this.selectOrg.orgsid.indexOf(data.uuid);
            // 如果不存在数组中,并且数组中已经有一个id并且checked为true的时候,代表不能再次选择。
            if (indexs < 0 && this.selectOrg.orgsid.length === 1 && checked) {
              // 设置已选择的节点为false 很重要
              this.$refs.tree.setChecked(this.selectOrg.orgJsn, false)//设置之前选中的为未选中
              this.selectOrg.orgsid = [];//清空
              this.selectOrg.orgsid.push(data.uuid);//存唯一的node-key中唯一的标致 uuid
              this.selectOrg.orgJsn=data;//存当前节点的json
              this.mainParentNode=this.$refs.tree.getNode(data)//用当前节点的值 来 获取当前节点在树中的位置,用于(增加/修改/删除)
            } else if (this.selectOrg.orgsid.length === 0 && checked) {
              // 发现数组为空 并且是已选择
              // 防止数组有值,首先清空,再push
              this.selectOrg.orgJsn=data;
              this.selectOrg.orgsid = [];
              this.selectOrg.orgsid.push(data.uuid);
              this.mainParentNode=this.$refs.tree.getNode(data);
            } else if (
              indexs >= 0 &&
              this.selectOrg.orgsid.length === 1 &&
              !checked
            ) {
              // 再次直接进行赋值为空操作
              this.selectOrg.orgsid = []
            }
    

    4.添加树:

          //将新创建的节点压入当前节点
          if (!this.mainParentNode.data.childList) {//查询有没有 childList ,用于存子节点
             this.$set(this.mainParentNode.data, 'childList', []);//没有就添加
           }
          this.mainParentNode.data.childList.push(data);//将生成的节点 data 压入当前节点 mainParentNode 的子节点数组 childList 中
    

    5.修改树:

          //修改相应字段,将当前的节点修改,对应修改
          this.selectOrg.orgJsn.字段名=this.mainParentNode.parent.data.字段名;//修改的节点 data.字段名
    

    6.删除树:

          //首先找到当前节点的父节点
          const children = this.mainParentNode.parent.data.childList || this.mainParentNode.parent.data;
          //通过 循环uuid 来找到对应删除的位置
          const index = children.findIndex(d => d.uuid === this.selectOrg.orgJsn.uuid);
          //splice删除
          children.splice(index, 1);
    

    相关文章

      网友评论

          本文标题:Element-ui中tree设置为单选及添加/修改/删除树

          本文链接:https://www.haomeiwen.com/subject/frecwqtx.html