vue实现charts树形
Vue 实现树形图表
在 Vue 中实现树形图表可以使用第三方库如 echarts 或 d3.js。以下是使用 echarts 和 d3.js 的两种方法。
使用 ECharts 实现树形图
安装 ECharts 依赖:

npm install echarts --save
在 Vue 组件中引入并使用:

<template>
<div ref="treeChart" style="width: 600px; height: 400px;"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
mounted() {
this.initTreeChart();
},
methods: {
initTreeChart() {
const chart = echarts.init(this.$refs.treeChart);
const option = {
series: [{
type: 'tree',
data: [{
name: 'Root',
children: [
{ name: 'Child 1' },
{ name: 'Child 2', children: [{ name: 'Grandchild' }] }
]
}],
orient: 'vertical',
symbol: 'circle',
symbolSize: 10,
label: {
position: 'top',
rotate: 0,
verticalAlign: 'middle',
align: 'right'
},
leaves: {
label: {
position: 'right',
verticalAlign: 'middle',
align: 'left'
}
},
expandAndCollapse: true,
animationDuration: 550,
animationDurationUpdate: 750
}]
};
chart.setOption(option);
}
}
};
</script>
使用 D3.js 实现树形图
安装 D3.js 依赖:
npm install d3 --save
在 Vue 组件中引入并使用:
<template>
<svg ref="treeSvg" width="600" height="400"></svg>
</template>
<script>
import * as d3 from 'd3';
export default {
mounted() {
this.initD3Tree();
},
methods: {
initD3Tree() {
const data = {
name: 'Root',
children: [
{ name: 'Child 1' },
{ name: 'Child 2', children: [{ name: 'Grandchild' }] }
]
};
const svg = d3.select(this.$refs.treeSvg);
const margin = { top: 20, right: 90, bottom: 30, left: 90 };
const width = 600 - margin.left - margin.right;
const height = 400 - margin.top - margin.bottom;
const treeLayout = d3.tree().size([width, height]);
const root = d3.hierarchy(data);
treeLayout(root);
const g = svg.append('g')
.attr('transform', `translate(${margin.left},${margin.top})`);
g.selectAll('.link')
.data(root.links())
.enter().append('path')
.attr('class', 'link')
.attr('d', d3.linkVertical()
.x(d => d.x)
.y(d => d.y));
const node = g.selectAll('.node')
.data(root.descendants())
.enter().append('g')
.attr('class', 'node')
.attr('transform', d => `translate(${d.x},${d.y})`);
node.append('circle')
.attr('r', 5);
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>
<style>
.link {
fill: none;
stroke: #ccc;
stroke-width: 2px;
}
.node text {
font: 12px sans-serif;
}
</style>
注意事项
- ECharts 适合快速实现交互式图表,支持丰富的配置项和动画效果。
- D3.js 更适合高度定制化的需求,但代码复杂度较高。
- 两种方法均需在 Vue 生命周期钩子(如
mounted)中初始化图表,确保 DOM 已渲染完成。






