1、创作缘由:一些用户可能有多个角色的身份,那用elementui树形控件的时候,因为id只能是唯一的,所以会导致有一些节点不处理的情况,现在要实现同一颗树下,相同id再勾选和回显的时候保持一致
2、大致思路:遍历树形控件的数据,添加一个额外的唯一key标识,然后根据这个key进行一些操作
3、关键代码:
4、代码:
// 遍历树形控件的方法!!!,主要的作用就是遍历每个节点,然后可以进行下一步key的添加
eachTreeData(data, callback, childKey) {
if (!childKey) childKey = 'children';
data.forEach((d) => {
if (callback(d) !== false && d[childKey])
this.eachTreeData(d[childKey], callback, childKey);
});
},
// 获取用户列表数据
async getroleList() {
this.nameLoding = true;
await roleList().then((res) => {
if (res.code == 200) {
this.data = res.data; //获取用户列表的数据,children类型的数据
this.addKeyToList(this.data);
}
});
this.nameLoding = false;
},
//给树的每一个节点 添加一个key(唯一值),并算出默认选中的节点key数组
addKeyToList(data) {
let key = 0;
this.eachTreeData(data, (d) => {
d.key = key++;
}); //遍历数据给每一个node添加一个key
this.checkedList = this.contrastList(data, []); //对比相同id的节点并获取key数组
},
//拿去后台传回来默认选中的节点id,返回该id对应的key的值,回显的数据处理
//这个方法的data是树形控件的数据列表,userId是后端返回的需要回显的id数组
contrastList(data, userId) {
let list = [];
if (userId) {
this.eachTreeData(data, (d) => {
userId.forEach((item) => {
//id相同就push一个key
if (item == d.id) {
// this.checkedList.push(d.key);
list.push(d.key);
}
});
});
} else {
list = [];
// this.checkedList = [];
}
// 返回回显的用户数据的唯一值key
// return this.checkedList;
return list;
},
//点击节点,判断该节点id是否有重复的,如果有相同id执行相同的操作(选中或取消选中)
setTeacherChecked(data, isChecked) {
let checkKey = [];
this.eachTreeData(this.data, (item) => {
if (data.id === item.id) {
console.log(item.id);
checkKey.push(item.key);
this.$refs.tree.setChecked(item.key, isChecked, false);
}
});
console.log(checkKey);
},
下面这个是上面那个举个例子的代码,这个可以看也可以不看哈
// 获取有限的指标权限对应的用户数据
async get_have_data_user(id) {
this.nameIndexLoding = true;
await indexRightUser({ code: id }).then((res) => {
this.userNum = res.data.length;
let userId = [];
res.data.forEach((element) => {
userId.push(element.id);
});
// console.log('指标对应的用户id', userId);
if (userId.length) {
let arr = [];
arr = this.contrastList(this.data, userId);
this.$refs.tree.setCheckedKeys(arr);
} else {
this.$refs.tree.setCheckedKeys([]);
}
//下面这两行代码因为我弄了tab 为了保证切换tab的时候数据还是回显的操作,监听tab的切换操作,切换了就发请求再次获取最新值
this.checkedList = this.contrastList(this.data, userId);
this.$refs.tree.setCheckedKeys(this.contrastList(this.data, userId));
if (this.index_have_user) {
this.$message({
type: 'success',
message: '修改成功!'
});
}
if (this.index_have_user_reset) {
this.$message({
type: 'success',
message: '重置成功!'
});
}
});
this.nameIndexLoding = false;
this.index_have_user = false;
this.index_have_user_reset = false;
},
5、参考:关于element-tree,解决id相同如何回显,同样的id只能选中一个的坑!!!!_element tree半选回显-优快云博客