由于项目需求,前端使用Extjs的treePanel组件做菜单,一个与后台交互的树形菜单需要三个重要的组件:
1、model:model作为数据源,是将后台传过来的json数据与前端统一。
例如:后台获取到一组对象集合List< User >,在User中使用@JsonProperty注解定义json名,此处省略get/set方法
这里需要注意的一点事引入json的注解包:,之前因为没注意,导致json字段重命名失败,ext又不认识name,数据展示不出来的情况。
public class TreeItem {
@JsonProperty("Id")
private Integer id;
@JsonProperty("text")
private String name;
@JsonProperty("ParentmenuID")
private String parentId;
private List<TreeItem> children= new ArrayList<TreeItem>();
@JsonProperty("leaf")
private boolean leaf;
那么页面上用定义数据源就是这样:
//树形菜单数据源
("ModuleStore", {
extend: "",
fields: [
{ name: "Id", mapping:"Id", type: "int" },
{ name: "text", mapping: "Mname", type: "string" },
{ name: "ParentmenuID", marpping: "ParentmenuID", type:"string" }
]
});
fields中对应的属性正是刚才json重命名的字段名,至于为什么要把name重命名为text,是因为之后要在treePanel里配置store,而treePanel只认属性为text的为名称;
2、创建store,一般组件创建store只需继承,但是作为treePanel的Store必须继承于。
关于store和model的关系,之前看过一篇文章,说的比较好。model相当于java中的对象,而store相当于为这些对象存储数据的集合。
var store = ("", {
fields: ["Id", "Mname", "ParentmenuID"],
proxy: {
type: "ajax",
url: "/user/",
reader:{
type:'json'
}
}
});
3、最后就是创建树形菜单,再将数据加进来
var treePanel = new ({
border: false,
autoScroll: true,
store: store,
rootVisible: false,
enable: false,
dataType: "json",//提交参数的数据类型
});
这样,将这个树形菜单加在ViewPort布局的west中,一个菜单功能基本就完成了。