Ext JS自定义表单字段:实现类似TemplateColumn的多模型字段展示
实现支持多字段模板渲染的自定义表单字段
核心方案
继承Ext.form.field.Display,新增模板配置项,通过监听模型数据变化,提取多字段数据后用模板渲染显示内容,实现类似GridPanel中TemplateColumn的效果。
代码实现
Ext.define('MyApp.form.field.TemplateDisplay', { extend: 'Ext.form.field.Display', alias: 'widget.templatedisplay', // 自定义模板配置,支持字符串或Ext.XTemplate实例 tpl: null, initComponent: function() { this.callParent(arguments); // 自动将字符串模板转为XTemplate实例 if (this.tpl && !(this.tpl instanceof Ext.XTemplate)) { this.tpl = new Ext.XTemplate(this.tpl); } }, // 重写绑定通知逻辑,处理多字段数据渲染 onBindNotify: function(me, newRecord) { if (this.tpl && newRecord) { // 提取模型全量数据,传入模板渲染 var recordData = newRecord.getData(); this.setValue(this.tpl.apply(recordData)); } else { this.callParent(arguments); } }, // 手动刷新渲染内容的方法 refreshDisplay: function() { var boundRecord = this.getBind().record; if (boundRecord && this.tpl) { this.setValue(this.tpl.apply(boundRecord.getData())); } } });
使用示例
在FormPanel中配置该字段,绑定模型并定义渲染模板:
Ext.create('Ext.form.Panel', { renderTo: Ext.getBody(), width: 400, bodyPadding: 10, viewModel: { data: { employee: { name: '张三', position: '前端开发', hireDate: '2020-05-10' } } }, items: [{ xtype: 'templatedisplay', fieldLabel: '员工详情', // 模板支持XTemplate的所有语法,比如格式化日期、条件判断 tpl: ` <div>姓名:{name}</div> <div>职位:{position}</div> <div>入职日期:{[Ext.Date.format(new Date(values.hireDate), 'Y年m月d日')]}</div> ` }], buttons: [{ text: '更新员工信息', handler: function() { this.up('form').getViewModel().set('employee', { name: '李四', position: 'UI设计师', hireDate: '2021-03-15' }); } }] });
关键说明
- 模板灵活性:
tpl支持Ext.XTemplate的所有特性,包括数据格式化、循环、条件渲染,满足复杂展示需求。 - 自动更新:绑定的模型数据变化时,
onBindNotify会自动触发,重新渲染内容。 - 手动控制:如果需要主动刷新显示,可调用
refreshDisplay方法。
内容的提问来源于stack exchange,提问作者user2022
相关产品推荐
相关产品推荐

