element UI树形控件,若子选中 父也要选中

树形控件html:

            <el-tree
              :data="trees"
              show-checkbox
              :default-expand-all="expandAll"
              :default-checked-keys="checkedKeys"
              node-key="id"
              ref="tree"
              @check="checkClick"
              highlight-current
              :props="defaultProps">
            </el-tree>

data:

data(){
    return{
      expandAll: false,
      checkedKeys: [],
      defaultProps: {
        children: "child",
        label: "title"
      },
      add: {
        name: null,
        status: 1,
        checked: false,
        rules: []
      },
      trees: [
        {
          id: 1,
          title: "一级 1",
          child: [
            {
              id: 4,
              title: "二级 1-1",
              child: [
                {
                  id: 9,
                  title: "三级 1-1-1"
                },
                {
                  id: 10,
                  title: "三级 1-1-2"
                }
              ]
            }
          ]
        },
        {
          id: 2,
          title: "一级 2",
          child: [
            {
              id: 5,
              title: "二级 2-1"
            },
            {
              id: 6,
              title: "二级 2-2"
            }
          ]
        }
      ]
    }
}

做权限管理的时候,若果有子集被选中了,父级也要被选中,最后把所有的id连接成一个数组发送给后端

官方文档中有这个方法,可以获取到半选中状态的父级的id集合,然后把选中的和半选中的通过concat连接成新数组。

  this.add.rules = this.add.rules.concat(
        this.$refs.tree.getHalfCheckedKeys()
  );

做完之后,再次编辑的时候获取后端数据,还是那个数组,需要过滤掉半选中的数据,重新设置好树形控件的选中状态。

解决办法:

在methods中写一个过滤函数

diguiquchu(datas, arr, v, i, needdelarr) {
      //递归找出半选中的数据
      arr.map((item, index) => {
        if (item.id == v && item.child) {
          // datas.splice(i, 1);//因为每次截取会改变原数组,所以不能这样
          needdelarr.push(v);
          this.diguiquchu(datas, item.child, v, i, needdelarr);
        } else if (item.id != v && item.child) {
          this.diguiquchu(datas, item.child, v, i, needdelarr);
        }
      });
    },

然后在点击编辑按钮时,后端返回的数据中调用上面的函数

      var url = api.saverolegroup;
      this.$http
        .get(url, { params: { id: row.id } })
        .then(res => {
          let data = res.data;
          if (data.code == 200) {
            var rules = data.result.rules;
            var needdelarr = [];
            rules.map((v, i) => {
              this.diguiquchu(
                data.result.rules,
                data.result.list,
                v,
                i,
                needDelArr
              );
            });
            console.log(needDelArr);
            console.log(rules);
            rules = rules.filter(item => !needDelArr.includes(item));
            console.log(rules);
            this.checkedKeys = rules;
          }
        })
        .catch(error => {
          console.log(error);
        });


 

猜你喜欢

转载自blog.csdn.net/bamboozjy/article/details/82465405