解决element-ui的el-tree组件设置默认选中,父级选中子级也被全部选中问题

el-tree结构代码

<el-tree ref="subRoleTree"
         :data="subRoleMenuList"
         show-checkbox
         node-key="id"
         :default-expanded-keys="tenantIdMenus" //默认展开指定节点
         :props="defaultProps">
</el-tree>
data() {
    return {
        subRoleMenuList: [],
        tenantIdMenus: [], //默认展开指定节点
        defaultProps: {
            children: 'children',
            label: 'name',
        },
    }
}

数据格式

{
    "msg": "请求成功",
    "code": 200,
    "menuTreeData": [{
        "id": "1",
        "name": "A",
        "children": [{
            "id": "01",
            "name": "A1",
            "children": [{
                "id": "001",
                "name": "A01",
                "children": []
            },
            {
                "id": "002",
                "name": "A02",
                "children": []
            },
            ]
        }]
    },
    {
        "id": "2",
        "name": "B",
        "children": []
    },
    {
        "id": "3",
        "name": "C",
        "children": []
    }]
}

el-tree 动态指定默认选中节点

// 权限分配列表数据
async getSubRoleMenus(id) {
    let {
        body
    } = await subRoleMenusGet({
        id
    }) if (body && JSON.stringify(body) !== '{}') {
        this.subRoleMenuList = body.menuTreeData
        this.$nextTick(_ = >{
            this.getTreeSelection(body.menuList)
        }) 
        console.log(body, 'getSubRoleMenus')
    }
},
//获取树结构选中数组
getTreeSelection(data) {
    data.forEach(i = >{
        // console.log(i)
        if (i.selected) {
            this.tenantIdMenus.push(i.id)
        }
        if (i.children) {
            this.getTreeSelection(i.children)
        }
        // console.log(i)
    }) 
        // console.log(this.tenantIdMenus, 'setIdMenus') 
        this.$nextTick(_ = >{
        // this.$refs.subRoleTree.setCheckedKeys(this.tenantIdMenus) //加载回显方法,会出现问题
        this.tenantIdMenus.forEach(value = >{
            this.$refs.subRoleTree.setChecked(value, true, false) //替换方案 解决问题
        })
    }) 
    this.$forceUpdate()
},

到此结束。

猜你喜欢

转载自blog.csdn.net/weixin_43743175/article/details/127199584