您的位置:首页 > 房产 > 家装 > 树组件 el-tree 数据回显

树组件 el-tree 数据回显

2024/10/6 14:38:07 来源:https://blog.csdn.net/qq_43730272/article/details/140774432  浏览:    关键词:树组件 el-tree 数据回显

树组件 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);}

实现效果:
在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com