最近项目中再做一个 选择为树组件的需求,页面内容大概为这样可折叠,可选择,(这里用的是element-ui的树结构可选择组件)在点击详情回显的时候,根据后台返回的数据(id),来勾选用户选择的信息
页面:
html代码
<div class="checkboxClass">
<el-tree :check-strictly="true" :data="allWorkList" :default-checked-keys="checkIds" @check='getname' show-checkbox node-key="id" ref="selectTree" @node-click="ncHandleNodeClick" :props="defaultProps" default-expand-all>
</el-tree>
</div>
以上用到的数组件属性有:
1 :default-checked-keys=“checkIds” 勾选上我们处理过后台数据拿到的id值,接收为数组形式的
( this. r e f s . s e l e c t T r e e . s e t C h e c k e d K e y s ) 放 在 t h i s . refs.selectTree.setCheckedKeys)放在this. refs.selectTree.setCheckedKeys)放在this.nexttick中使用,切记两者一定要搭配使用,否则会更新错误
2 @check=‘getname’ 可以拿到当前点击的节点数据
methods方法
getname(node, checkedNodes) {
console.log(node, checkedNodes);// 当前点击节点,点击之前的所有选中节点加当前节点
this.selectTreeArr = this.$refs.selectTree.getCheckedNodes();
},
选择后,把每条数据的id给截取下来,传给后台
selectSub() {
this.selectDialog = false;
this.modal = false;
this.selectIds = this.selectTreeArr.map(v => {
return v.id;
}).join(',');
console.log('处理括号后的数组', this.selectTreeArr);
console.log('this.selectIdsthis.selectIds', this.selectIds);
},
点击当前条的详情回显得时候,拿到后台返回数据给到的id ,与选择的id,提交回传给后台
workClickFocus() {
this.selectDialog = true;
console.log('选择的值', this.selectTreeArr);
let workNameList = this.selectTreeArr.map(item => item.id);
this.allWorkList = this.workTree;
let a = this.getIds(this.workTree); // 利用递归把里面的每项items给拿出来
console.log('aaaaa的值', a);
for (let i = 0; i < a.length; i++) {
if (workNameList.includes(a[i])) {
let b = a[i];
this.$set(this.checkIds, this.checkIds.length, b);
}
}
console.log('this.checkeds的值', this.checkIds);
this.$nextTick(() => {
this.$refs.selectTree.setCheckedKeys(this.checkIds);
});
},
这个方法,你使用 :default-checked-keys="checkIds" 必须用 this.$refs.selectTree.setCheckedKeys去更新我们的数据,否则他还会去存上一次的值,不会清空,这个踩坑了花了一下午时间后来才知道是因为他
this.$nextTick(() => {
this.$refs.selectTree.setCheckedKeys(this.checkIds);
});
this.getIds 递归方法去拿我们的子项id(这个方法在我其他博客里面,如果用到可以去复制一下)
上面说的是我们如何拿到可选择的树结构id,以及 default-checked-keys更新错误的问题,如果你已经解决下面的就不用看了
扩展点: (也记录下)
项目中有个限制,不能选择父节点,所以要用这个方法做限制
formatTree(list) {
list.forEach(child => {
if (child.items && Array.isArray(child.items) && child.items.length > 0) {
child.disabled = true;
this.formatTree(child.items);
}
});
},
在初始化获取列表的时候我们在把list那个树结构给传进去
initWorkClick() {
const self = this;
systemApi.getPositionTree().then(res => {
if (res.code === 0) {
this.workTree = res.data.treenodelist;
**this.formatTree(this.workTree);**
console.log('this.workTree', this.workTree);
this.allWorkList = this.workTree[0].items;
console.log('this.allWorkLitd的值', this.allWorkList);
}
let treeData =
res && res.data && res.data.treenodelist && Array.isArray(res.data.treenodelist)
? res.data.treenodelist
: [];
self.gwfilterParams.forEach(item => {
if (item.type === 'treeSelect' && item.valueCode === 'gwbh') {
console.log('岗位的item', item);
item.options = treeData;
}
});
}).catch(err => {
if (err) {
this.$message.error(err.msg);
return false;
}
});
},