(g6)紧凑树布局点击节点添加子数据
效果
代码
//创建容器
<div class="bigDiv-left">
<div id="container"></div>
</div>
mounted() {
this.container(); //紧凑树
},
//方法
container() {
//2.创建关系图
const width = document.querySelector("#container").clientWidth;
const height = document.querySelector("#container").clientHeight;
const graph = new G6.TreeGraph({
container: "container",
width,
height,
modes: {
default: [
{
type: "collapse-expand", //类型
onChange: function onChange(item, collapsed) {
const data = item.getModel();
data.collapsed = collapsed;
return true;
},
},
"drag-canvas",
"zoom-canvas",
],
},
defaultNode: {
size: 26,
anchorPoints: [
[0, 0.5],
[1, 0.5],
],
},
defaultEdge: {
type: "cubic-horizontal",
},
layout: {
type: "compactBox",
direction: "LR",
defalutPosition: [],
getId: function getId(d) {
return d.id;
},
getHeight: function getHeight() {
return 16;
},
getWidth: function getWidth() {
return 16;
},
getVGap: function getVGap() {
return 10;
},
getHGap: function getHGap() {
return 100;
},
},
});
// 节点设置
graph.node(function (node) {
return {
label: node.label,
labelCfg: {
offset: 10,
position:
node.children && node.children.length > 0 ? "left" : "right",
},
};
});
//3.配置数据源,渲染
graph.data(g6test43); //g6test43为需渲染的数据
graph.render();
graph.fitView();
if (typeof window !== "undefined") {
window.onresize = () => {
if (!graph || graph.get("destroyed")) return;
if (!container || !container.scrollWidth || !container.scrollHeight)
return;
graph.changeSize(container.scrollWidth, container.scrollHeight);
};
}
//点击节点添加子节点数据
graph.on("node:click", function (evt) {
const item = evt.item;
const nodeId = item.get("id");
console.log(nodeId);
const model = item.getModel();
const children = model.children;
if (!children || children.length === 0) {
const childData = [
{
id: "child-data-" + 0,
label: "toString",
},
{
id: "child-data-" + 1,
label: "equals",
},
{
id: "child-data-" + 2,
label: "distance",
},
];
const parentData = graph.findDataById(nodeId);
console.log(parentData);
if (!parentData.children) {
parentData.children = [];
}
// 如果childData是一个数组,则直接赋值给parentData.children
// 如果是一个对象,则使用parentData.children.push(obj)
parentData.children = childData;
graph.changeData();
}
});
},