如下图所示,对节点常用的事件如下图所示:
主要代码:
// 鼠标进入节点
this.graph.on('node:mouseenter', (e) => {
const nodeItem = e.item // 获取鼠标进入的节点元素对象
console.log('鼠标移入', nodeItem._cfg)
})
// 单击节点
this.graph.on('node:click', (e) => {
const nodeItem = e.item // 获取被点击的节点元素对象
console.log('单击', nodeItem._cfg)
})
// 双击节点
this.graph.on('node:dblclick', (e) => {
const nodeItem = e.item // 获取被点击的节点元素对象
console.log('双击', nodeItem._cfg)
})
完整代码:
<template>
<div>
<div id="container"></div>
</div>
</template>
<script>
import G6 from '@antv/g6'
export default {
name: 'g6',
mounted () {
this.initComponent()
},
data () {
return {
data: {}, // 拓扑图数据
graph: undefined // new G6
}
},
methods: {
/**
* 创建G6,并对G6的一些设置
* */
initComponent () {
this.data = {
nodes: [
{
id: 'node1',
label: '采集服务器',
ip: '192.168.1.1',
status: 0
// 此处的key值一定不要出现type,如果出现type,图片修改无效
},
{
id: 'node2',
label: '数据库',
ip: '192.168.1.2',
status: 1
},
{
id: 'node3',
label: '终端',
ip: '192.168.1.3',
status: 2
},
{
id: 'node4',
label: '引擎',
ip: '192.168.1.4',
status: 0
}
],
edges: [
{
source: 'node1',
target: 'node2'
},
{
source: 'node1',
target: 'node3'
},
{
source: 'node1',
target: 'node4'
}
]
}
/**
* 遍历节点数据,给节点添加图片
*/
for (let i = 0, len = this.data.nodes.length; i < len; i++) {
// eslint-disable-next-line eqeqeq
if (this.data.nodes[i].status == 0) { // 'offlineAnomaly'
this.data.nodes[i].img = 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2Ftp05%2F19100122420C335-0-lp.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1641970684&t=70b9b0b3a05f6ca5d56d6c4234fdd1fd'
}
// eslint-disable-next-line eqeqeq
if (this.data.nodes[i].status == 1) { // 'onlineAuth'
this.data.nodes[i].img = 'https://yyb.gtimg.com/aiplat/page/product/visionimgidy/img/demo6-16a47e5d31.jpg?max_age=31536000'
}
// eslint-disable-next-line eqeqeq
if (this.data.nodes[i].status == 2) { // 'onlineAuth'
this.data.nodes[i].img = 'https://img0.baidu.com/it/u=3927459320,2138990686&fm=26&fmt=auto'
}
}
this.graph = new G6.Graph({
container: 'container',
width: 800,
height: 800,
layout: {
type: 'force',
preventOverlap: true, // 防止节点重叠
// 防碰撞必须设置nodeSize或size,否则不生效,由于节点的size设置了40,虽然节点不碰撞了,但是节点之间的距离很近,label几乎都挤在一起,所以又重新设置了大一点的nodeSize,这样效果会好很多
nodeSize: 100,
linkDistance: 150 // 指定边距离为150
},
defaultNode: { // 节点样式修改
type: 'image', // 设置节点为图片
size: [40, 40] // 节点大小
},
modes: {
default: ['drag-canvas', 'zoom-canvas', 'drag-node'] // 允许拖拽画布、放缩画布、拖拽节点
}
})
this.graph.data(this.data)
this.graph.render()
// 鼠标进入节点
this.graph.on('node:mouseenter', (e) => {
const nodeItem = e.item // 获取鼠标进入的节点元素对象
console.log('鼠标移入', nodeItem._cfg)
})
// 单击节点
this.graph.on('node:click', (e) => {
const nodeItem = e.item // 获取被点击的节点元素对象
console.log('单击', nodeItem._cfg)
})
// 双击节点
this.graph.on('node:dblclick', (e) => {
const nodeItem = e.item // 获取被点击的节点元素对象
console.log('双击', nodeItem._cfg)
})
}
}
}
</script>