前端关系图谱组件 relation-graph 实战指南
relation-graph 是一款开源免费的关系图谱组件,支持 Vue2、Vue3 和 React 框架。它提供开箱即用的体验,配置简单,文档清晰,并支持通过插槽自定义节点样式。该组件具有高度可定制性,支持节点点击事件等交互功能,适用于构建各种关系图谱应用。
快速开始
1. Vue2 使用
安装
npm install --save relation-graph
代码示例
在 Vue 组件中引入并使用:
<template>
<div>
<RelationGraph
ref="graphRef"
:options="graphOptions"
:on-node-click="onNodeClick"
:on-line-click="onLineClick"
/>
</div>
</template>
<script>
import RelationGraph from 'relation-graph'
export default {
name: 'Demo',
components: { RelationGraph },
data() {
return {
graphOptions: {
defaultJunctionPoint: 'border'
}
}
},
mounted() {
this.showGraph()
},
methods: {
showGraph() {
const jsonData = {
rootId: 'a',
nodes: [
{ id: 'a', text: 'A', borderColor: 'yellow' },
{ id: 'b', text: 'B', color: '#43a2f1', fontColor: 'yellow' },
{ id: 'c', text: 'C', nodeShape: 1, width: 80, height: 60 },
{ id: 'e', text: 'E', nodeShape: 0, width: 150, height: 150 }
],
lines: [
{ from: 'a', to: 'b', text: '关系 1', color: '#43a2f1' },
{ from: 'a', to: 'c', text: '关系 2' },
{ from: 'a', to: 'e', text: '关系 3' },
{ from: 'b', to: 'e', color: '#67C23A' }
]
}
this.$refs.graphRef.setJsonData(jsonData)
},
onNodeClick(nodeObject, $event) {
console.log('onNodeClick:', nodeObject)
},
onLineClick(lineObject, $event) {
console.log('onLineClick:', lineObject)
}
}
}
</script>
2. Vue3 使用
安装
npm install --save relation-graph-vue3
代码示例
配合 <script setup> 使用:
<template>
<div>
<relation-graph ref="graphRef" :options="options" />
</div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import RelationGraph from 'relation-graph-vue3'
const graphRef = ref()
const options = {
defaultExpandHolderPosition: 'right'
}
onMounted(() => {
const jsonData = {
rootId: 'a',
nodes: [
{ id: 'a', text: 'a' },
{ id: 'b', text: 'b' },
{ id: 'c', text: 'c' },
{ id: 'd', text: 'd' },
{ id: 'e', text: 'e' },
{ id: 'f', text: 'f' },
],
lines: [
{ from: 'a', to: 'b' },
{ from: 'a', to: 'c' },
{ from: 'a', to: 'd' },
{ from: 'a', to: 'e' },
{ from: 'a', to: 'f' },
],
}
graphRef.value.setJsonData(jsonData)
})
</script>



