后台(ASP.NET Core WebAPI,目标框架.net 7,除FreeSql外,用到包WinReal.Base)
(相关资料图)
前端(TDesign Starter 0.7.2 + vue 3.2.45)
控件(TDesign TreeSelect控件)
对应数据结构
public class Dept
{
[Column(IsIdentity = true, IsPrimary = true)]
public int DeptId { get; set; }
public string DeptName { get; set; } = "";
public int ParentId { get; set; }//父级DeptId
public int OrderId { get; set; }//当前节点完整子树起始,本身节点次序值
public int MaxOrderId { get; set; }//当前节点完整子树最后一个节点的次序值
public int Depth { get; set; }//当前节点所在深度,TDesign中用不到
}
1.后端传递数据的模型,结构适用于TDesign的t-tree控件
public class TreeNode
{
public string Value { get; set; } = "";
public string Label { get; set; } = "";
public Boolean Children { get; set; } = false;
public List<TreeNode>? Kids { get; set; }
}
2.后端每次只返回指定父级的直隶子级
public Result<List<TreeNode>> GetDeptKidNodes(int parentId)
{
Result<List<TreeNode>> result = new();
List<TreeNode> nodes = new List<TreeNode>();
var depts = _fsql.Select<Dept>().Where(a => a.ParentId == parentId).OrderBy(a => a.OrderId).ToList();
TestLog(JsonSerializer.Serialize(depts));
foreach (Dept dept in depts)
{
TestLog(dept.DeptName);
if (dept.OrderId == dept.MaxOrderId)
{
nodes.Add(new TreeNode { Value = dept.DeptId.ToString(), Label = dept.DeptName, Children = false });
}
else
{
nodes.Add(new TreeNode { Value = dept.DeptId.ToString(), Label = dept.DeptName, Children = true, Kids = DeptGetKids(dept.DeptId) });
}
}
if (nodes == null)
{
result.Err("没有子部门");
}
else
{
result.Data = nodes;
}
return result;
}
3.前端逐级展开
①api接口:src\api\model\basicinfoModel.ts
export interface TreeNodeModel {
value: string;
label: string;
children: boolean;
kids?: Array<TreeNodeModel>;
}
②api接口:src\api\basicinfo.ts
const Api = {
DeptKidNodes: '/BasicInfo/GetDeptKidNodes',
};
export function getDeptKidNodes(parentId) {
return request.get({
url: Api.DeptKidNodes,
params: { parentId },
});
}
③vue文件template
<t-tree ref="tree" :data="items" checkable hover :load="load" />
④vue文件setup script
import { getDeptKidNodes } from '@/api/basicinfo';
import { TreeNodeModel } from '@/api/model/basicinfoModel';
const items = ref<Array<TreeNodeModel>>([
{
value: '0',
label: '部门管理',
children: true,
},
]);
const load = (node) =>
new Promise((resolve) => {
setTimeout(async () => {
const nodes = await getKids(node.value);
resolve(nodes);
}, 1000);
});
const getKids = async (parentId) => {
const result = await getDeptKidNodes(parentId);
return result;
};