![](http://static.blog.csdn.net/images/category_icon.jpg)
1 树(Tree Panel)
在Web应用程序开发中,Tree Panel使用的频率很高。Tree Panel是ExtJS的核心组件之一,Tree Panel和Grid Panel一样都是从相同的类(Ext.panel.Table)扩展,因此Tree Panel具有Grid Panel的所有功能,Grid Panel的features、extensions和plugins在Tree Panel也能使用。Tree Panel的实现非常方便,通过以下代码就能生成一个简单的Tree。
- Ext.create('Ext.tree.Panel', {
- renderTo: Ext.getBody(),
- title: 'Simple Tree',
- width: 150,
- height: 150,
- root: {
- text: 'Root', //树的根节点文本
- expanded: true, //展开Root节点
- children: [ //根节点(Root)的子节点数组
- {
- text: 'Child 1', //子节点的显示文本
- leaf: true //是否为叶子节点,true表示该节点是叶子节点
- },
- {
- text: 'Child 2',
- leaf: true
- },
- {
- text: 'Child 3',
- expanded: true, //展开节点
- children: [ //节点的子节点数组
- {
- text: 'Grandchild',
- leaf: true
- }
- ]
- }
- ]
- }
- });
- var store = Ext.create('Ext.data.TreeStore', {
- root: {
- text: 'Root',
- expanded: true,
- children: [
- {
- text: 'Child 1',
- leaf: true
- },
- {
- text: 'Child 2',
- leaf: true
- },
- ...
- ]
- }
- });
- Ext.create('Ext.tree.Panel', {
- title: 'Simple Tree',
- store: store, //绑定上面创建的TreeStore
- ...
- });
2 多列树(Multiple columns)
Tree Panel和Grid Panel一样可以显示多列数据,从代码上看,多列树和普通的Grid Panel的区别在于,多列树的columns中必须有一个列是treecolumn。
- var tree = Ext.create('Ext.tree.Panel', {
- renderTo: Ext.getBody(),
- title: 'TreeGrid',
- width: 300,
- height: 150,
- fields: ['name', 'description'], //字段
- columns: [{
- xtype: 'treecolumn', //把列的类型设置成treecolumn
- text: 'Name',
- dataIndex: 'name', //绑定name字段
- width: 150,
- sortable: true
- }, {
- text: 'Description',
- dataIndex: 'description', //绑定description字段
- flex: 1,
- sortable: true
- }],
- root: { //树的根节点,也就是TreeStore的快捷方式
- name: 'Root', //根节点name字段的值
- description: 'Root description', //根节点description字段的值
- expanded: true, //展开根节点
- children: [{ //根节点的子节点数组
- name: 'Child 1',
- description: 'Description 1',
- leaf: true
- }, {
- name: 'Child 2', //节点name字段的值
- description: 'Description 2', //节点description字段的值
- leaf: true
- }]
- }
- });
3 添加树节点
树的根节点(Root)可以晚绑定,也就是在创建树时不配置树的根节点,等树创建完以后再给树添加根节点。
- var tree = Ext.create('Ext.tree.Panel'); //创建空树,该树没有添加节点数据
- tree.setRootNode({ //通过setRootNode方法给树添加根节点
- text: 'Root', //根节点显示文字
- expanded: true,
- children: [{ //根节点的子节点数组
- text: 'Child 1',
- leaf: true
- }, {
- text: 'Child 2',
- leaf: true
- }]
- });
- //附加子节点
- var root = tree.getRootNode(); //获取树的根节点
- var parent = root.appendChild({ //在根节点中添加父节点
- text: 'Parent 1'
- });
- parent.appendChild({ //在父节点中添加子节点
- text: 'Child 3',
- leaf: true
- });
- //插入子节点
- var child = parent.insertChild(0, { //在第一个位置插入子节点
- text: 'Child 2.5',
- leaf: true
- });
- parent.insertBefore({ //在child节点前面插入节点
- text: 'Child 2.75',
- leaf: true
- }, child);