Ant Design of Vue -- 实现树形结构的只能选最下层数据及只默认展开选中的数据

1. 展示形式

在这里插入图片描述

2. 代码实现

2.1 样式实现

<a-tree v-model="checkedKeys" checkable :tree-data="treeData" :expanded-keys="expandedKeys"
        @expand="onExpand" @check="onCheck" />
/**
* @func:打开分配菜单抽屉
 * @param:{object} record -- 行数据
 * */
showMenu(id){
    this.visible = true;
    this.id = (typeof id === "object"?id.id:id);
    this.isEquipment = (typeof id === "object"?id.isEquipment:false); // 判断是否是从设备列表中传过来的数据
    this.expandedKeys = []; // 关闭所有展开的项
    this.getExpandData = [];
    this.$api.mock(this.URL.getMenu + this.id, {method: "get"}).then(res => {
        if (res.data.httpStatus === 200) {
            // 选中项
            this.checkedKeys = res.data.data.checkedIds;
            // 数据:一般情况
            if (!this.isChildId) this.treeData = res.data.data.arrTree;
            // 数据:需要给父级设置disabled的情况
            if (this.isChildId) this.getDisabled(res.data.data.arrTree);
            // 设备列表菜单:需要展开关联的房屋数据
            if(this.isEquipment && res.data.data.checkedIds){
                this.getExpand(res.data.data.arrTree,this.checkedKeys[0]);
                this.expandedKeys = this.getExpandData;
            }
        }
    })
},

/**
 * @func:展开关闭
 * @param:{object} record -- 行数据
 * */
onExpand(expandedKeys) {
    this.expandedKeys = expandedKeys;
},

2.2 只能选最下层数据

/**
 * @func:设置 disabled 属性
 * @param:{array} data -- 树数据
 * */
getDisabled(data) {
    data.forEach(item => {
        if (item.children) {
            item.disabled = true;
            this.getDisabled(item.children)
        }
        this.treeData = data;
    });
},

2.3 默认只展开选中的数据

/**
 * @func:展开关联的房屋
 * @param:{array} data -- 树数据
 * @param:{String} targetKey -- 目标数据的key
 * */
getExpand(data,targetKey) {
    for(let index=0;index<data.length;index++){
        if(data[index].children){
            // 递归查询到最下层数据
            this.getExpand(data[index].children,targetKey);
        }
        // 找到选中数据的父节点(最上层的父节点是“0”)
        if(data[index].key === targetKey && data[index].parentId !== "0"){
            this.getExpandData.push(data[index].parentId);
            // 逐层向上查找父节点
            this.getExpand(this.treeData,data[index].parentId);
        }
    }
},

后台传过来的数据只有选中数据的key值,但是展开需要其父级的所有key值,因此需要递归遍历。

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值