vue2用D3组件的treemap,写一个横向的树状图,不要矩形,要连线,类似于脑图的效果
时间: 2024-04-15 15:28:08 浏览: 115
好的,以下是一个使用Vue 2和D3.js创建横向树状图(类似脑图)的示例代码:
```vue
<template>
<div ref="chartContainer"></div>
</template>
<script>
import * as d3 from 'd3';
export default {
mounted() {
// 数据示例
const data = {
name: 'Root',
children: [
{ name: 'A', children: [
{ name: 'A1' },
{ name: 'A2' },
{ name: 'A3' }
]},
{ name: 'B', children: [
{ name: 'B1' },
{ name: 'B2' }
]},
{ name: 'C', children: [
{ name: 'C1' },
{ name: 'C2' },
{ name: 'C3' },
{ name: 'C4' }
]}
]
};
// 创建树状布局
const treeLayout = d3.tree()
.size([500, 300])
.nodeSize([100, 50]);
// 构建层次数据
const root = d3.hierarchy(data);
// 计算树状布局
treeLayout(root);
// 创建SVG容器
const svg = d3.select(this.$refs.chartContainer)
.append('svg')
.attr('width', 500)
.attr('height', 300);
// 创建连线
const links = svg.selectAll('.link')
.data(root.links())
.enter()
.append('path')
.attr('class', 'link')
.attr('d', d3.linkHorizontal()
.x(d => d.y)
.y(d => d.x));
// 创建节点
const nodes = svg.selectAll('.node')
.data(root.descendants())
.enter()
.append('g')
.attr('class', 'node')
.attr('transform', d => `translate(${d.y},${d.x})`);
// 绘制节点圆圈
nodes.append('circle')
.attr('r', 10)
.style('fill', 'steelblue');
// 绘制节点文本
nodes.append('text')
.attr('dy', 5)
.attr('dx', 15)
.text(d => d.data.name)
.style('fill', 'black');
}
};
</script>
<style scoped>
.link {
fill: none;
stroke: #ccc;
stroke-width: 1.5px;
}
.node circle {
fill: steelblue;
}
.node text {
font-size: 14px;
}
</style>
```
这个示例使用了D3的树状布局(treeLayout)来创建横向的树状图,并通过连线(links)和节点(nodes)来表示树的结构。连线使用了`linkHorizontal`生成器,节点使用圆圈和文本来表示。
希望这个示例能满足你的需求!如果有任何问题,请随时提问。
阅读全文
相关推荐















