关于Ext框架的树使用记录——页面对结点追加和移除
1、在官方API例子中观察得知,一颗tree的形成需要创建TreeStore(需要一个根节点root)、挂载树的容器Panel。
//官网demo
var store = Ext.create('Ext.data.TreeStore', {
root: {
expanded: true,
children: [
{ text: 'detention', leaf: true },
{ text: 'homework', expanded: true, children: [
{ text: 'book report', leaf: true },
{ text: 'algebra', leaf: true}
] },
{ text: 'buy lottery tickets', leaf: true }
]
}
});
Ext.create('Ext.tree.Panel', {
title: 'Simple Tree',
width: 200,
height: 150,
store: store,
rootVisible: false,
renderTo: Ext.getBody()
});
2、创建一个Panel,并且item使用treepanel,生成tree的根节点
Ext.create('Ext.Panel', {
width: 500,
height: 300,
title: "FormLayout Panel",
layout: 'form',
renderTo: Ext.getBody(),
bodyPadding: 5,
items: [
{
xtype: 'treepanel',
region: 'center',
name:"searchTreePanel",
width: 400,
rootVisible: false,
store: Ext.create('Ext.data.TreeStore', {
root: {
expanded: true,
children: [{
id:"treenode",
text: '条件列表',
level:"homegroup",
expanded: true,
iconCls: "fa fa-cog",
children: [] //后续生成的节点会塞到这里
}]
}
}),
listeners:{
afterrender:function(){
//默认选择根节点
var record = this.getStore().getNodeById('treenode');
this.getSelectionModel().select(record)
},
beforeitemclick( t, record, item, index, e, eOpts ){
//点击事件 ,将隐藏在节点的数据重新显示在表单上
var formData=record.data.config.tempValue;
Form.getForm().setValues(formData);
Form.expand(true);//打开侧边栏
}
}
}]
});
3、对树的操作,先获取树对象,可以使用全局搜索组件方法:Ext.ComponentQuery.query(),但如果有其它更好的方式不推荐使用全局搜索方式。
对节点的操作(暂不讨论修改)
- 构建子节点node
- 判断追加的节点是同级还是子级
- 操作树节点
//控制器
var childData={
id:cid, //结点id,不能重复
text:zd_zw+where_zw+value, //节点显示的文本
tempValue:formData, //自定义临时变量值
iconCls: "fa fa-heart", //节点图标
level:level,//层级
leaf:false //是否展开节点
};
var newNode=Ext.create('Ext.data.NodeStore',childData ); //创建节点
4、找到选中的节点:var selectRoot=tree.selection;//选中的节点 tree指的是获取的tree对象
5、如果是追加子级,找到它的子节点,使用appendChild()方法
selectRoot.appendChild(newNode);6、如果是追加兄弟节点,则找到所选节点的父节点,使用appendChild()方法
var newNode=Ext.create('Ext.data.NodeStore',childData );
selectRoot.parentNode.appendChild(newNode);7、移除节点
tree.selection.remove(); //移除选中的
8、遍历树生成层级数据结构
(在递归时需要注意对象的类型,如果是引用类型,后续的操作会影响原始数据【即重复数据】,直到页面刷新对象被释放)
//控制器
//child指的树传入树的根节点进行递归处理
//var child= Object.assign([],items[0].childNodes);
//使用Object.assign()方法处理对象克隆,防止改变原始数据
traverseTree:function(child,type) {
var temp=[];
var location=0;//递归的层级
var forFn=(function(child,type){
for(var i=0;i<child.length;i++){
if(child[i].childNodes.length>0){
temp.push({"parent":Object.assign({},child[i].data.config)});
location=i;
forFn(child[i].childNodes,"dg");
}else{
if(type=="dg"){
if(!temp[location]["parent"].hasOwnProperty("children")){
//属性不存在时
temp[location].parent.children=Object.assign([],child[i].data.config);//追加属性用
}else{
//追加数组用push
temp[location].parent.children.push(Object.assign({},child[i].data.config));
}
}else{
temp.push({"parent":Object.assign({},child[i].data.config)});
}
}
}
});
forFn(child);
//console.log("temp",temp);
return temp;
}
大概的数据结果:
// 只是提供一个思路,代码部分截取于项目代码。