项目中遇到的需求,就是根据已选择的id,遍历树形控件,只允许用户选择变量ids里面的id下面的children数据,其他都要禁用,不能选择,下面是代码:
<template>
<el-tree
:check-strictly="true"
:data="showData"
show-checkbox
node-key="id"
:default-expanded-keys="ids"
:props="defaultProps"
:default-checked-keys="ids"
>
</el-tree>
</template>
<script>
export default {
data() {
return {
data: [
{
id: 1,
name: "胖胖family",
children: [
{
id: 11,
name: "胖胖股份有限公司",
children: [
{
id: 111,
name: "事业部",
children: [],
},
{
id: 112,
name: "兼职部",
children: [
{
id: 1121,
name: "电商",
children: [],
},
],
},
],
},
{
id: 22,
name: "胖胖股份外部合作伙伴",
children: [
{
id: 221,
name: "总裁办公室",
children: [],
},
{
id: 222,
name: "特别服务部",
children: [],
},
{
id: 223,
name: "全面预算委员会",
children: [],
},
{
id: 224,
name: "经营管理中心",
children: [],
},
{
id: 225,
name: "产品设计",
children: [],
},
],
},
{
id: 33,
name: "胖胖股份有限公司",
children: [
{
id: 331,
name: "总经理办公室",
children: [],
},
],
},
],
},
],
defaultProps: {
children: "children",
label: "name",
},
ids: [112,33],
showData: [],
};
},
mounted() {
this.addDis(this.data);
this.showData = this.data;
},
methods: {
addDis(data) {
data.forEach((item) => {
const hasIds = this.ids.indexOf(item.id);
if (hasIds == -1) {
item["disabled"] = true;
} else {
item["disabled"] = true;
return;
}
if (item.hasOwnProperty("children")) {
this.addDis(item["children"]);
}
});
},
},
};
</script>