树组件 el-tree 数据回显
树型结构的数据回显问题:
这里我只放了核心代码,主要是如何获取选中的树节点的id集合和如何根据树节点的id集合回显数据
大家根据需要自行更改!
<el-tree ref="authorityRef" node-key="id" :data="allAuthorityList" show-checkbox default-expand-all empty-text="加载中,请稍候" :props="defaultProps"> </el-tree>
const authorityRef = ref(ElTree)const defaultProps = {children: 'childrenList',label: 'name'}//1、如何获取选中的树节点的id集合!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!//我这里是通过Tree 组件的`getCheckedNodes`方法先获取到当前选中节点的数组然后再取其id值const checkedMenuAllIds = authorityRef.value.getCheckedNodes(false, true).map((node: any) => node.id)//如果传参要求只要最后一级的id值,可以再过滤处理一下const checkedMenuAllIds: number[] = authorityRef.value.getCheckedNodes(false, true).filter((node) => !node.childrenList || node.childrenList.length === 0).map((node) => Number(node.id)) //只传最后一级的id//2、如何根据树节点的id集合回显数据!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!//首先肯定是获取到树结构数据,为确保DOM更新后才调用setChecked,我这里使用nextTick//获取成功后,我这里是通过Tree 组件的`setChecked`方法设置节点是否被选中// 获取树级列表const { executeBody: fetGetCheckLibraryTree } = useRequest(api_get_checkLibrary_Tree(), {onSuccess(res: any) {allAuthorityList.value = res//注意:确保数组里面的id类型与树形结构中的id类型匹配!//这里的props.checkedAllId就是树节点的id集合,例如[ "1","574850805256267","574850805260359","574850805260357","574850805260361"]if (props.checkedAllId) {// 回显已拥有的结构nextTick(() => {props.checkedAllId.forEach((id) => {authorityRef.value?.setChecked(id, true, false)//核心代码就这一句!})})}}})
如果后端返回的数据不是树节点的id集合组成的数组结构,这里我的后端给我的是树型结构,我是通过递归处理的
// 递归函数来提取 checkIdsfunction extractCheckIds(checkIds, result: string[]) {checkIds.forEach((checkId) => {result.push(checkId.id);if (checkId.childrenList && checkId.childrenList.length > 0) {extractCheckIds(checkId.childrenList, result);}});}//使用时if (res.checkIds && res.checkIds.length > 0) {const checkedAllIds: string[] = [];extractCheckIds(res.checkIds,checkedAllIds);}
实现效果: