Kendo Grid如何将父行关联的对象列表转换为父行下方的新行
实现方案
你要的层级展示效果可以通过「扁平化数据构造+Kendo Grid列模板控制」实现,具体步骤如下:
步骤1:构造适配展示的数据源
不要直接使用合并了Month和Week属性的ViewModel,你需要先把一对多的层级数据拍平为列表,每条数据新增ItemType字段标识行类型(值为Month或Week),整体按「月份行→该月所有周行→下一个月份行→该月所有周行」的顺序排序:
Month类型行:仅填充月份相关字段(编号、月份名、月开始/结束时间、勾选状态),周相关字段留空Week类型行:仅填充周相关字段(周名、周编号、周开始/结束时间、工时、锁定状态),月份相关字段留空
注意:你原来的表头有重名列(两个
num、两个Start、两个end),对应数据源里要给不同的字段名,比如月份编号叫monthNum、周编号叫weekNum,避免绑定冲突。
步骤2:配置Kendo Grid
通过列模板控制不同类型行的内容展示,参考配置代码如下:
$("#grid").kendoGrid({ // 列定义,按你要的表头顺序配置 columns: [ { title: "[ ]", // 仅月份行显示勾选框 template: `# if(ItemType === 'Month') { # <input type="checkbox" #= isChecked ? 'checked' : '' # disabled /> # } else { # # } #` }, { field: "monthNum", title: "num" }, { field: "monthName", title: "month" }, { field: "monthStart", title: "Start", format: "{0:MM/dd}" }, { field: "monthEnd", title: "end", format: "{0:MM/dd}" }, { field: "weekName", title: "week", // 周行加缩进,更直观体现层级 template: `# if(ItemType === 'Week') { # <span style="padding-left: 24px">#= weekName #</span> # } else { # # } #` }, { field: "weekNum", title: "num" }, { field: "weekStart", title: "start", format: "{0:MM/dd}" }, { field: "weekEnd", title: "end", format: "{0:MM/dd}" }, { field: "hours", title: "hour" }, { field: "isLocked", title: "Lock", template: `# if(ItemType === 'Week') { # #= isLocked ? 'Yes' : 'No' # # } else { # # } #` } ], dataSource: { data: processedFlatData, // 替换为你第一步构造好的扁平数组 schema: { model: { fields: { ItemType: { type: "string" }, monthNum: { type: "number" }, monthStart: { type: "date" }, monthEnd: { type: "date" }, weekNum: { type: "number" }, weekStart: { type: "date" }, weekEnd: { type: "date" }, hours: { type: "number" }, isLocked: { type: "boolean" } } } } }, sortable: false, // 关闭排序避免打乱月份+周的固定顺序 pageable: false });
可选拓展:实现折叠/展开功能
如果需要点击月份行折叠/隐藏下属周行,只需要给Grid加行点击事件,判断点击的是月份行时,切换它后面所有连续的同月份Week行的显示状态即可。
内容的提问来源于stack exchange,提问作者VAC
相关产品推荐
相关产品推荐

