extjs Ext.grid.Panel表格组件学习

extjs Ext.grid.Panel表格组件学习

Summary

概述

Grids are an excellent way of showing large amounts of tabular data on the client side. Essentially a supercharged

, GridPanel makes it easy to fetch, sort and filter large amounts of data.

表格是一个非常优秀的方法展现大量表格形式的数据在客户端。table的基本增强,表格面板可以轻易的获取、排序和过滤大量数据。

Grids are composed of two main pieces - a Ext.data.Store full of data and a set of columns to render.表格由两个主要部分组成 - 一个是Ext.data.Store整个数据和 一组要渲染的列。

Ext.create('Ext.data.Store', {
    storeId: 'simpsonsStore',
    fields:[ 'name', 'email', 'phone'],
    data: [
        { name: 'Lisa', email: '[email protected]', phone: '555-111-1224' },
        { name: 'Bart', email: '[email protected]', phone: '555-222-1234' },
        { name: 'Homer', email: '[email protected]', phone: '555-222-1244' },
        { name: 'Marge', email: '[email protected]', phone: '555-222-1254' }
    ]
});

Ext.create('Ext.grid.Panel', {
    title: 'Simpsons',
    store: Ext.data.StoreManager.lookup('simpsonsStore'),
    columns: [
        { text: 'Name', dataIndex: 'name' },
        { text: 'Email', dataIndex: 'email', flex: 1 },
        { text: 'Phone', dataIndex: 'phone' }
    ],
    height: 200,
    width: 400,
    renderTo: Ext.getBody()
});

`

Height config with bufferedRenderer: true

高度配置在配置项bufferedRenderer: true的情况下

The height config must be set when creating a grid using bufferedRenderer: true and the grid’s height is not managed by an owning container layout. In Ext JS 5.x bufferedRendering is true by default.

高度必须被配置,在使用bufferedRenderer: true情况下,表格的高度不在自身的容器布局管理。在extjs5.x中这个值默认是true。

Renderers

渲染器

As well as customizing columns, it’s easy to alter the rendering of individual cells using renderers. A renderer is tied to a particular column and is passed the value that would be rendered into each cell in that column. For example, we could define a renderer function for the email column to turn each email address into a mailto link:

对于自定义的列,可以很方便的转换每个独立的单元使用渲染器。一个渲染器绑定在特定的列上传递给被渲染列的单元值。例如:我们可以定义一个渲染函数对于邮件列转换每个邮件为一个邮件链接。

columns: [
    {
    
    
        text: 'Email',
        dataIndex: 'email',
        renderer: function(value) {
    
    
            return Ext.String.format('<a href="mailto:{0}">{1}</a>', value, value);
        }
    }
]

查看更多See the Ext.grid.column.Column for more information on renderers.

总结: 查看这个列类,里面有renderer方法,如下:
renderer : Function / String
A renderer is an ‘interceptor’ method which can be used to transform data (value, appearance, etc.) before it is rendered. Example:
NOTE: In previous releases, a string was treated as a method on Ext.util.Format but that is now handled by the formatter config.
Defaults to: false
renderer是一个“拦截器”方法可以用来转换数据在它渲染前。

store :  Ext.data.Store
The data store
renderer: function (value, metaData, record, rowIndex, colIndex, store) {
    
    
    // style the cell differently depending on how the value relates to the
    // average of all values
    var average = store.average('grades');
    metaData.tdCls = (value < average) ? 'needsImprovement' : 'satisfactory';
    return value;
}

Selection Models

选择模型

Sometimes you simply want to render data for viewing, but usually it’s necessary to interact with or update that data. Grids use a concept called a Selection Model, which is simply a mechanism for selecting some part of the data in the grid. The two main types of Selection Model are RowSelectionModel, where entire rows are selected, and CellSelectionModel, where individual cells are selected.

有事你简单的想看数据,但是有时你需要交互和更新数据。Grids使用了一个叫选择模型的概念,是一个简单选择表格中一部分数据的机制。有两个主要选择模型一个是行选择模型,他是整行选择,一个是单元选择模型,独立的单元格选择。

Grids use a Row Selection Model by default, but this is easy to customize like so:

表格默认使用行选择模型,但是很容易如下自定义

Ext.create('Ext.grid.Panel', {
    
    
    selModel: 'cellmodel',
    store: ...
});

Specifying the cellmodel changes a couple of things. Firstly, clicking on a cell now selects just that cell (using a Ext.selection.RowModel will select the entire row), and secondly the keyboard navigation will walk from cell to cell instead of row to row. Cell-based selection models are usually used in conjunction with editing.

制定单元格模型改变了很多事情。首先,单击一个单元格现在选择的只是一个单元格(xxx),其次键盘导航(就是上下左右键)将是一个单元格到一个单元格的跳,而不是行到行。单元格基础的选择模型经常用在连同编辑。

You may also utilize selModel as a config object for an instance of Ext.selection.Model.

你也可以利用selModel作为一个配置对象(Ext.selection.Model实例)。

For example:

selModel: {
selType: ‘cellmodel’,
mode : ‘MULTI’
}
This allows you to modify additional selection model configurations such as:

这可以容许你修改多个选择模型配置,例如:

mode - Specifies whether user may select multiple rows or single rows
allowDeselect - Specifies whether user may deselect records (when in SINGLE mode)
ignoreRightMouseSelection - Specifies whether user may ignore right clicks for selection purposes

mode - 制定是否哦那个可以选择多个行或单个行; ?
?
?

Ext.grid.column.Action xtype: actioncolumn

Summary

概述

A Grid header type which renders an icon, or a series of icons in a grid cell, and offers a scoped click handler for each icon.
表格头类型渲染一个图标或者一系列图标在单元格中,提供一组点击处理对于每个图标。

常见配置项

bbar : Object / Object[]
Convenience config. Short for ‘Bottom Bar’.
bbar: [
{ xtype: ‘button’, text: ‘Button 1’ }
]

列线,显示表格中的列那条线,默认是false
columnLines: true,

Ext.grid.plugin.CellEditing plugin: plugin.cellediting

总结

  1. columns: [ 中配置的就是列名字
    下面是常用的配置项:
  • xytpe: 列类型
  • text: 列头显示文字
  • width: 宽度 //width: 140,不带单位,默认是px
  • sortable:是否可排序,默认是
  • hideable:是否可隐藏,默认是 // hideable:false,
  • format: 格式化字符串,常用与日期、数字的格式化。 日期:‘Y-m-d’或’Y-m-d H:i:s’ 保留两位小数0.00 不保留小数0
  • renderer:自定义绘制方法。
  • editor:编辑器,当使用编辑插件的时候才会起作用。

gird常用配置项:

  • stripeRows: true 斑马线效果
  • columnLines: true 控制中间是否有线相隔
  1. grid分页

注意:1) 注意pagingtoolbar的store配置一定要和grid的store相同。
2) 经测试,每页显示多少行,放到store中,当在pagingtoolbar对象中不启作用。
pageSize : 20,

分页一般在下面,设置底部条属性 bbar:返回Ext.PagingToolbar对象即可

initComponent: function()
{
    Ext.applyIf(this,{});
    this.actionStore = this.getActionData();
    this.store = this.getGStore();
    this.tbar = this.getTbar();
    this.bbar = this.getBbar();
    this.callParent(arguments);
},
getBbar: function()
{
    return Ext.create('Ext.PagingToolbar',
            {
                store : this.getGStore(),
                cls:'page',
                displayInfo : true,
                displayMsg : '显示 {0} - {1} 条,共计 {2} 条',
                emptyMsg : "没有数据"
            });
},
getGStore: function()
{
    if (this.store)
    {
        return this.store;
    }
    return Ext.create('Ext.data.Store',
            {
                pageSize : 20,
                fields : [ 'add_time', 'type','level', 'desc'],
                autoLoad : true,
                proxy : {
                    type : 'ajax',
                    url : '/JF/Public_SystemLog/getWarnLog/',
                    reader : {
                        type : 'json',
                        rootProperty : 'list',
                        totalProperty : 'allRow'
                    },
                    simpleSortMode : true
                }
            });
},    
  1. 使用复选框来选择行

     selModel: {
     	selType: 'checkboxmodel',
     	mode   : 'MULTI'      //“SINLE” "SIMPLE" "MULTI"
         checkOnly: true  //只能通过checkbox选择
     },
    

除了界面操作选择行,我们可以通过代码选择行:

//选择行,并保持其他行的选择状态
grid.getSelectionModel().select(records,true);
//选择所有
grid.getSelectionModel().selectAll();
//根据row index选择
grid.getSelectionModel().selectRange(startRow, endRow, true);

获取选中行
var records = grid.getSelectionModel().getSelection();

  1. 显示行号 {xtype: ‘rownumberer’},
    行号列名怎么加? 试了text不行

     columns:[
         {xtype: 'rownumberer'},
     	{ 
     		text: '时间',   
     		sortable: true,
     		width: 140,
     		dataIndex: 'add_time' 
     	},
    
  2. 表格中添加图片
    在columns:[ 子组件(列)中的renderer事件回调返回图片即可

{
    
     
    text: '链路状态',   
    sortable: false,    
    hideable:false,
    dataIndex: 'link_status', 
    flex: 1,
    renderer: function (val, m) {
    
    
            if ('1' == val) {
    
    
                return '<img src="/Public/image/start.gif"';
            }
            return '<img src="/Public/image/stop.gif"';
        }
},
  1. 在columns:[ 子组件(列)中,dataIndex的值,在store中没有定义,那么这个列名还是会显示出来,不过单元格没有内容。
    { text:"操作", dataIndex:'response_name', flex:1 }

  2. 动态给表格添加一行
    在ext表格中,动态添加行主要和表格绑定的sotre有关。
    通过对store数据集进行添加或删除,就能实现表格行的动态添加和删除。

1) 动态添加表格的行
gridStore.add({});
2)动态删除表格的行
girdStore.removeAt(gridStore.count() - 1);
var gridStore= Ext.getCmp('riskFunc').getStore(); gridStore.removeAt(gridStore.count() - 1);

  1. 动态增删列:
    在ext表格中,动态添加列主要通过修改表格绑定的column元素,通过对column元素集进行添加或删除,然后重新渲染表格,就能实现列的动态添加删除
    var gridTable = Ext.create(‘Ext.grid.Panel’,{});
  • 添加列:
cols.push({
    
    
    text:'列',
    dataIndex:'col'
});

gridTable.reconfigure(gridStore,cols); //调用该方法重新配置的时候,会重新载入store

reconfigure ( [store] , [columns] ) 
Reconfigures the grid or tree with a new store and/or columns. Stores and columns may also be passed as params.
  • 动态删除表格的列
    cols.pop();
    gridTable.reconfigure(gridStore,cols);
  1. 把grid中的数据添加到form.Panel表单中?
    两种情况,第一种formpanel数据源和grid相同,使用form.getForm().loadRecord(row);则数据自动加载在formpanel对应的控件上。
    a)从grid的store中获取记录
    b)使用表单面板组件的loadRecord()将grid中选择记录的数据复制到form中;

     	/* 2017-5-19
     	//grid record added to form
     	var gridFormStore = Ext.getCmp('riskFunc').getStore();
     	var record = gridFormStore.getAt(0);
     	form.loadRecord(record);
     	*/
    

第二种情况: formpanel数据源是单独的,则store传入到formpanel页面后,还需要手动将formpanel中的每个控件用value赋值。(这里一般适用第二种情况)
把grid中的数据加载到form

  1. 表格编辑,为需要编辑的列指定编辑器,在columns中
    编辑器可以是一个field配置,以可以是一个xtype。
    如:

    	columns: [
    		    { text: '程序名称',  dataIndex: 'name', editor: 'textfield', flex:1},
                                                        // editor:{xtype:"numberfield"}
    

对于编辑后的单元格,会在左上角出现一个红色的标识,说明该数据被编辑过,要想去掉这个红色箭头,需要调用record的commit方法。

    grid.on('edit',function(editor,e){
    
    
        //
        e.record.commit();
    });

//实践:在grid的配置项中添加监听 edit事件
			selModel: 'cellmodel',
			plugins: {
    
    
				ptype: 'cellediting',
				clicksToEdit: 1
			},
			listeners: {
    
    
					edit: function(editor, e){
    
    
						e.record.commit();
						console.log(e);
                        //e.value 当前你编辑的字段值
                        //e.record 当前编辑的记录record
					}
			}
  1. 将grid中的数据保存为arrayjson
    思路,取得store对象取出记录集遍历记录,使用记录的方法data取记录(直接json这个) Ext.JSON.encode(record.data);然后push到一个数组中

    var gridFormStore = Ext.getCmp('riskFunc').getStore();
    	var records = gridFormStore.getData();
    				console.log(records.getCount());
    				console.log(records.getAt(0));
    	var jsonArray = [];
    	var tempgrid = '';
    	gridFormStore.each(function(record){
    		/*
    		var currentRecord = record.get('master');
    		var currentRecord = record.get('range');
    		var currentRecord = record.get('name');
    		var currentRecord = record.get('type');
    		*/
    		var currentRecord = record.get('master') + record.get('range') + record.get('name') + record.get('type');
    		console.log('currentRecord:'+ currentRecord);
    		if(currentRecord){
    			tempgrid = tempgrid + currentRecord;
    			jsonArray.push(Ext.JSON.encode(record.data));
    		} 
    	});
    
  2. panel添加多行工具栏(panel,formpanel,gridpanel)
    网上多推荐是思路1和思路3
    思路1:先把grid渲染,然后通过render事件的监听,在它被渲染时候添加多条工具栏。
    思路2:layout属性
    思路3:使用buttongroup
    思路4:使用dockedItems

1)在grid中增加监听事件render,才能添加多行tabr

//未测试成功
listeners:{
    
    
	'render':function(){
    
    

		var tbar2 = new Ext.Toolbar({
    
    
			items:[
				'第二行工具栏',
				'-',
				{
    
    
					text:'查询',
					iconCls: 'search'
			
				},
				'-'
			]
		});
		tbar2.render(this.tbar); //add one bar
	}
},

3)实践buttongroup ,TODO//,网上大多推荐该方法。

  tbar: [{
    
    
        xtype: 'buttongroup',
        columns: 3,         //分成3列
        items: [{
    
    
            text: 'Paste',
            scale: 'large',     //配置不同大小的按钮, small 小按钮;medium 中等按钮; large大按钮
            rowspan: 3,              //占三行
            iconCls: 'add',
            iconAlign: 'top',
            cls: 'btn-as-arrow'
        },{
    
    
            text: 'Copy', iconCls: 'add16'
        },{
    
    
            text: 'Format', iconCls: 'add16'
        }]
    }],

//尝试tbar中使用两个buttongroup,还是不中,这两个之间还是水平布局的。

  tbar: [{
    
    
        xtype: 'buttongroup',
        //columns: 3,
        items: [{
    
    
            text: 'Paste',
            scale: 'large',
            rowspan: 3,
            iconCls: 'add',
            iconAlign: 'top',
            cls: 'btn-as-arrow'
        },{
    
    
            text: 'Copy', iconCls: 'add16'
        },{
    
    
            text: 'Format', iconCls: 'add16'
        }]
    },
	{
    
    
        xtype: 'buttongroup',
        //columns: 3,
        items: [{
    
    
            text: 'Paste',
            scale: 'large',
            rowspan: 3,
            iconCls: 'add',
            iconAlign: 'top',
            cls: 'btn-as-arrow'
        },{
    
    
            text: 'Copy', iconCls: 'add16'
        },{
    
    
            text: 'Format', iconCls: 'add16'
        }]
    }	
		],

4)推荐此方法,在grid的配置项中,加如下配置,它会附加一个工具在你的工具栏上方

 dockedItems: [{
    
    
		xtype: 'toolbar',
		dock: 'top',
		items: [{
    
    
			text: 'Docked to the top'
		}]
	}],

猜你喜欢

转载自blog.csdn.net/inthat/article/details/131265721
今日推荐