1、
javascript
<el-table
border
:header-cell-style="tableStyle?.headerCellStyle"
ref="tableRef"
:data="tableData"
row-key="id"
:default-expand-all="false" // 默认不展开所有树形节点
:tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
/*
配置树形结构的属性,
children:指定子节点数据的字段名,
hasChildren:指定一个布尔值字段,表示是否有子节点
这样组件就知道如何递归渲染树形结构。*/
lazy // 启用懒加载模式(子节点数据不会一次性加载,而是当用户展开某个节点时,通过load方法动态加载)
:load="load"
/*
指定懒加载时调用的方法,这里绑定的是load方法。
当用户展开一个节点时,会触发这个方法,传入当前行的数据和resolve回调函数,用于异步加载子节点数据。
*/
></el-table>
import { treeByParentId } from '/@/api/admin/dept';
const tableData = ref([])
let nowRowId = ref('')
const getTableList = (parentId) => {
return new Promise(resolve => {
treeByParentId({parentId}).then(res => {
if(res.code == 0 && Array.isArray(res.data)){
resolve(res.data)
} else {
resolve([])
useMessage().error(res.msg || '数据已加载完毕')
}
}).catch(() => {
resolve([])
})
})
}
const load = async (row, treeNode, resolve) => {
if (!row.hasChildren) {
return resolve([])
} else {
nowRowId.value = row.id
const data = await getTableList(row.id)
row.children = data
resolve(data)
}
}
const getData = async (parentId = nowRowId.value) => {
// 查询的时候,如果deptName的值不为空,parentId置为空
if(state.queryForm.deptName != ''){
parentId = ''
}
const { data } = await treeByParentId({ parentId, deptName: state.queryForm.deptName })
tableData.value = data
}
onMounted(() => {
getData()
})
// 重置
const reset = () => {
nowRowId.value = ''
state.queryForm.deptName = ''
getData()
}
2、
接口的数据结构:
javascript
{
"code": 0,
"data": [
{
"id": "唯一标识",
"name": "节点名称",
"hasChildren": true, // 必须字段!
"children": [] // 必须字段(即使为空数组)
},
// ...其他节点
]
}