g6中多个树图分别根据数据多少来重新设置高度,进而保持所有树图大小基本一致
作者:互联网
template中页面代码
<div v-for="(item, index) in treeData" :key="index">
<div :id="item[tree].id" class="graph-wh"></div> //树图容器(根据传递来的多个树型数据数组)
</div>
树图对数据格式有要求,必须有id和children两个字段
官网数据格式示例:
https://g6.antv.vision/zh/graphmarker
script中
<script lang="ts">
import { Vue, Component, Prop } from 'vue-property-decorator'
import G6 from '@antv/g6'
@Component
export default class TreeGraph extends Vue {
@Prop({
type: Array,
default () {
return []
}
})
treeData!: any; //树形数据列表
@Prop({
type: String,
default: ''
})
tree!: string; //根据自己数据格式自己定义,因为我树形数据列表还包含其他属性,就传递了一下树数据对应的字段
@Prop({
type: Object,
default: {}
})
treeProp!: any; //这个也是根据自己数据格式定义的字段名称
public createTreeGraph (treeData: any) {
treeData.forEach((item: any) => { //循环创建多个树图
const data = item[this.tree] //得到树结构数据
const container: any = document.getElementById(item[this.tree].id) //获得容器
const width = container.scrollWidth
const height = container.scrollHeight || 500 //容器宽高
const that = this
const graph = new G6.TreeGraph({
container: container,
width,
height,
modes: {
default: [
{
type: 'tooltip',
formatText (model: any) {
return model[that.treeProp.remark] //交互行为,定义了一下tooltip展示的数据
},
offset: 10
}
]
},
defaultNode: { //节点大小及从节点那个方向伸出线和进入线
size: 26,
anchorPoints: [
[0, 0.5],
[1, 0.5]
]
},
defaultEdge: {
type: 'cubic-horizontal' //边样式,生态树,紧凑树可能不是同一级别的子节点在一个级别上
},
layout: { //布局,设置了节点之间高度宽度,等等
type: 'compactBox',
direction: 'LR', // H / V / LR / RL / TB / BT
getHeight: () => {
return 16
},
getWidth: () => {
return 16
},
getVGap: () => {
return 15
},
getHGap: () => {
return 130
}
}
})
graph.node((node: any) => { //设置了label位置和个别节点的填充颜色
return {
label: node[that.treeProp.nameType] + ':' + node[that.treeProp.field],
labelCfg: {
position: node.children && node.children.length > 0 ? 'top' : 'right',
offset: 5
},
style: {
fill: node[that.treeProp.target] ? 'red' : '#1890ff'
}
}
})
graph.data(data) //传入数据
graph.render() //渲染
graph.fitView() //自适应
const zoom: any = graph.getZoom().toFixed(2) //获得自适应后缩小的放大的倍数
const toToal = Math.ceil(height / zoom) //现在的高度除以倍数获得应该的高度
container.style.height = toToal + 'px'
graph.changeSize(width, toToal) //重新设置高度
graph.fitView([0, 20])//重新自适应
if (typeof window !== 'undefined') {
window.onresize = () => {
if (!graph || graph.get('destroyed')) return
if (!container || !container.scrollWidth || !container.scrollHeight) return
graph.changeSize(container.scrollWidth, container.scrollHeight)
}
}
})
}
//mounted方法
public mounted () {
this.$nextTick(() => {
this.createTreeGraph(this.treeData)
})
}
}
</script>
css中
<style lang="scss">
.graph-wh { //容器高度
position: relative;
width: 100%;
height: 300px;
}
.g6-tooltip { //tooltip样式要自己设
position: relative;
max-width: 250px;
padding: 4px 6px;
color: #fff;
white-space: pre-line;
background-color: rgba(0, 0, 0, 0.5);
border: 1px solid #e2e2e2;
border-radius: 4px;
}
</style>
标签:node,g6,基本一致,return,graph,树图,container,any,const 来源: https://blog.csdn.net/qq_39692513/article/details/113174785