This article mainly records the operations to be performed when the two nodes in the antv X6 canvas are successfully connected
graph.on('edge:connected', ({ isNew,edge }) => {
// 这里的isNew是一个布尔值,代表两个节点是否连接成功 true为成功 false为失败
if (isNew) {
const sourceId = edge.getSourceCell().id // sourceId为源节点id
const targetId = edge.getTargetCell().id // targetId为剪头指向的节点id
// 当拿到这两个id就可以做一些操作了 举个例子:
let arr =[{ label:'', children:[] }]
if (sourceId && targetId) {
arr[0].label=sourceId
arr[0].children.push(targetNode)
}
})
As shown in the figure below, you can see that the two ids are node 1 and node 2 respectively.
![](https://img-blog.csdnimg.cn/img_convert/e67db01f6441da9d30a7ac6460883ccc.png)
Of course, if you do not customize the node id when adding nodes, then the id is the default (a long list...) Just set it like this when adding nodes:
let count = 0
let node = graph.addNode({
shape: 'custom-rect',
label: type,
x: -50,
y: -50,
id: `节点${++count}`, // 设置节点id
})
By the way, if the node id is modified after the node is generated, it is not possible! ! ! Modified by direct assignment! ! !
比如这样:
node.id = '666'
这是错误的❌方法
You can only use the official method of antv X6, path refers to the path, and value refers to the content you want to modify (if you really don’t know, just print the node directly to see what information it has)
![](https://img-blog.csdnimg.cn/img_convert/3f32648967d4e2ce044eb5fc7b43eaa1.png)
![](https://img-blog.csdnimg.cn/img_convert/7bc8bc54f07a5ae5e7e48fe838cb88ff.png)
If you want to use the modified information to do some operations when the two nodes are successfully connected after modifying the node information, then only one of the above modification methods will achieve the desired effect, that is, when adding nodes Directly modify the id you want (that is, the operation of addNode), because when the graph.on('edge:connected') node is connected, the edge points to the information of the old node, not the new one
When you need to find whether there is a node id you specified in the canvas, and operate on the node, you can use this method:
const findId = (data) => {
const curID = data.label // 这个是你指定的id值
const selectedNode = graph.getCellById(curID) // 在画布中查找是否有节点id等于curID
// 这里说明一下,你一定要区分cell和node的关系,确认清楚你要的是cell的id还是node的id 我这里取的是cell
console.log(selectedNode,'selectedNode')
if (selectedNode) {
reset(graph)
selectedNode.attr('body/stroke', 'red') // 如果有 该节点边框颜色会变成红色
}
}
The above content is only a summary of personal front-end learning. If there is anything wrong, welcome to communicate and learn together~~~
(ps: If you have time later, take a small demo of vue3+antv X6 2.0+elemnet plus~ This may make it easier to understand some operations)