vue树状图中实现
在Vue中实现树状图(Tree Diagram)通常可以通过第三方库或自定义组件完成。以下是几种常见方法:
使用第三方库(如vue-orgchart)
安装vue-orgchart库:
npm install vue-orgchart
在Vue组件中引入并使用:
<template>
<orgchart :datasource="treeData"></orgchart>
</template>
<script>
import OrgChart from 'vue-orgchart'
export default {
components: { OrgChart },
data() {
return {
treeData: {
name: 'Root',
children: [
{ name: 'Child 1' },
{ name: 'Child 2', children: [{ name: 'Grandchild' }] }
]
}
}
}
}
</script>
使用d3.js实现自定义树状图
安装d3.js:
npm install d3
创建自定义树状图组件:
<template>
<div ref="treeContainer"></div>
</template>
<script>
import * as d3 from 'd3'
export default {
props: ['data'],
mounted() {
this.renderTree()
},
methods: {
renderTree() {
const width = 800
const height = 600
const margin = { top: 20, right: 90, bottom: 30, left: 90 }
const svg = d3.select(this.$refs.treeContainer)
.append('svg')
.attr('width', width)
.attr('height', height)
const g = svg.append('g')
.attr('transform', `translate(${margin.left},${margin.top})`)
const treeLayout = d3.tree().size([height - margin.top - margin.bottom, width - margin.left - margin.right])
const root = d3.hierarchy(this.data)
const treeData = treeLayout(root)
// 绘制连线
g.selectAll('.link')
.data(treeData.links())
.enter()
.append('path')
.attr('class', 'link')
.attr('d', d3.linkHorizontal()
.x(d => d.y)
.y(d => d.x))
// 添加节点
const node = g.selectAll('.node')
.data(treeData.descendants())
.enter()
.append('g')
.attr('class', 'node')
.attr('transform', d => `translate(${d.y},${d.x})`)
node.append('circle')
.attr('r', 10)
node.append('text')
.attr('dy', '.31em')
.attr('x', d => d.children ? -13 : 13)
.style('text-anchor', d => d.children ? 'end' : 'start')
.text(d => d.data.name)
}
}
}
</script>
使用递归组件实现简单树状结构
对于简单的树状结构,可以通过递归组件实现:
<template>
<ul>
<li v-for="node in treeData" :key="node.id">
{{ node.name }}
<tree-node v-if="node.children" :treeData="node.children"></tree-node>
</li>
</ul>
</template>
<script>
export default {
name: 'TreeNode',
props: ['treeData']
}
</script>
调用方式:

<template>
<tree-node :treeData="treeData"></tree-node>
</template>
<script>
import TreeNode from './TreeNode.vue'
export default {
components: { TreeNode },
data() {
return {
treeData: [
{
id: 1,
name: 'Parent',
children: [
{ id: 2, name: 'Child 1' },
{ id: 3, name: 'Child 2' }
]
}
]
}
}
}
</script>
以上方法可根据需求复杂度选择,第三方库适合快速实现标准树状图,自定义方案则灵活性更高。





