我有如下所示的 api 响应数据结构。我的数据是动态的,可能会发生变化。数据结构有子级。它可能有孩子中的任何孩子,时间未确定。最后一个孩子有一片叶子,它的值是真实的,但其他作为父母的叶子是真实的。
[
{
"Id": 16456,
"ParentId": null,
"Title": "گروه تهران",
"MapLayerGroupTypeId": "1",
"leaf": false,
"children": [
{
"Id": 16457,
"ParentId": "16456",
"Title": "آب",
"MapLayerGroupTypeId": "1",
"leaf": false,
"children": [
{
"Id": 22334,
"MapLayerGroupId": "16457",
"Title": "maaber_97",
"leaf": true
}
]
},
{
"Id": 16458,
"ParentId": "16456",
"Title": "پایه",
"MapLayerGroupTypeId": "1",
"leaf": true,
"children": []
},
]
},
{
"Id": 16462,
"ParentId": null,
"Title": "",
"MapLayerGroupTypeId": "1",
"leaf": false,
"children": [
{
"Id": 16463,
"ParentId": "16462",
"Title": "title1",
"MapLayerGroupTypeId": "1",
"leaf": true,
"children": []
},
{
"Id": 16464,
"ParentId": "16462",
"Title": "title2",
"MapLayerGroupTypeId": "1",
"leaf": true,
"children": []
},
{
"Id": 16465,
"ParentId": "16462",
"Title": "title3",
"MapLayerGroupTypeId": "1",
"leaf": true,
"children": []
}
]
}
]
我想使用 ExtJs 在树视图中显示它。
我编写如下代码并且它有效:
Ext.define('Gis.view.MapLayer.MapLayerTreePanelPublic', {
extend: 'Ext.tree.Panel',
xtype: 'public_gis_tree_panel',
controller: 'public_gis_map_layer',
renderConfig: {
gisMap : null
},
title: 'لایههای مکانی',
baseToolbar: false,
displayField: 'Title',
rootVisible: false,
checkPropagation: 'both',
reference: 'publicGisTreeMap',
tools: [
{
type: 'expand',
tooltip: 'بازکردن همه',
callback: 'onExpandLayerTree'
},
{
type: 'collapse',
tooltip: 'بستن همه',
callback: 'onCollapseLayerTree'
},
],
initComponent: function () {
let me = this;
me.loadData();
me.callParent();
},
listeners: {
checkchange: 'onTreeCheckChanged',
itemclick: 'onTreeItemClick',
itemcontextmenu: 'showContextMenu'
},
loadData: function () {
let me = this;
Ext.Ajax.request({
url: BASE.GIS_MODULE_URL + 'map-layer-group/index',
method: 'POST',
jsonData: {
typeCode: "public"
},
success: function (response) {
let result = Ext.decode(response.responseText);
if (result.success) {
const setNodeChecked = (nodes) => {
return nodes.map(node => {
if (node.leaf) {
node.checked = false; // Set initial checked state to false
} else if (node.children) {
node.children = setNodeChecked(node.children);
}
return node;
});
};
let processedData = setNodeChecked(result.data.items);
let store = Ext.create('Ext.data.TreeStore', {
root: {
expanded: true,
children: processedData
},
fields: [{
name: 'iconCls',
convert: function (v, rec) {
if (!rec.data.leaf) {
return 'x-fa fa-map';
}
if (rec.get('StylePreview')) {
let styleElement = document.createElement('style');
styleElement.type = 'text/css';
styleElement.innerHTML = `
.x-tree-icon${rec.get('Id')} {
background-image: url("data:image/png;base64, ${rec.get('StylePreview')}") !important;
background-position: center !important;
background-size: cover !important;
}`;
document.head.appendChild(styleElement);
return `x-tree-icon${rec.get('Id')}`; // Icon for leaf nodes with a preview
}
}
}],
});
// Set store after data is processed
me.setStore(store);
}
},
});
},
});