用d3+vue实现一个可折叠的树状图
背景
前两天接到了一个需求,监控系统要实现一个可以折叠展开的树状图来展示完整的接口调用链,同时右侧要展示一些接口的相关信息诸如耗时、调用时间、返回值之类的。
Demo
先在网上找了个demo,完美符合了需求。
Demo地址:点击跳转demo
效果预览
接下来就是在demo的基础上加一些自定义的东西丰富下树状图,先给大家看一下效果:
展开状态:
折叠状态:
代码
设计思路很简单,先把demo封装成一个方法,返回值就是html代码,直接在父组件里通过操作dom替换成新的树状图,这样就可以完成展开折叠包括数据刷新后树状图的更新,不过感觉不是封装的很好,之后准备把一些展示的列相关的数据配置成变量。
下面是tree.js的代码:
import * as d3 from 'd3'
export const Tree = (data, {
width = 1000, }, funcs) => {
let i = 0;
const root = d3.hierarchy(data).eachBefore(d => d.index = i++);
const nodes = root.descendants();
//node size
const nodeSize = 20;
//链路图右侧数据展示配置
const columns = [
{
label: 'StartTime',
value: d => {
return d.traceRawData.startTime
},
format: (d, type) => {
if (type === 'value') {
let startTime = d.data.traceRawData.startTime;
if (startTime === null) {
return '-';
}
else {
return startTime.slice(0, 10) + ' ' + startTime.slice(11, 19);
}
}
if (type === 'color') {
return 'black'
}
if (type === 'font-weight') {
return 'none'
}
},
x: 420
},
{
label: 'RetCode',
value: d => {
return d.traceRawData.tretCode
},
format: (d, type) => {
if (type === 'value') {
let retCode = d.data.traceRawData.tretCode;
if (retCode === null) {
return '-';
}
else {
return retCode.slice(0, 10) + ' ' + retCode.slice(11, 19);
}
}
if (type === 'color') {
return 'black'
}
if (type === 'font-weight') {
return 'none'
}
},
x: 570
}
]
//链路图右侧耗时展示
const cost = [
{
label: 'Cost',
value: d => {
return d.traceRawData.duration
},
format: (d, type) => {
if (type === 'value') {
let duration = d.data.traceRawData.duration;
if (duration === null) {
return '-'
}
if (duration > 1000) {
if (duration > 1000000) {
return (duration / 1000000).toFixed(1) + 's'
}
else {
return