Vue3使用echarts tree高度自适应支持滚动查看

1,577 阅读1分钟

最近使用echarts tree写了一个组件,写了固定的高,发现当展开的节点特别多的时候,节点就会重叠在一起(如下图),显示效果不好,就做了一些展示优化。

image.png

思路

一开始tree的高度是固定写死的,现在根据节点的数量高度自适应,节点就不会重叠到一起。支持滚动查看。

实现(主要代码)

<template>
  <div style="overflow: auto; height: calc(80vh)">
      <div id="treechart" style="height: 800px"></div>
  </div>
</template>

<script setup lang="ts">
import * as Echarts from "echarts";
import { ref,onMounted } from "vue";
onMounted(()=>{
    let chartDom = Echarts.init(document.getElementById("treechart"));
    let option={
        ....
    };
    chartDom.setOption(option);
    chartDom.on("click",function(event){
        let treeDom = document.getElementById("treechart");//获取元素
        if(event.componentType === "series"){
            let nodeList = Array.from(new Set(chartDom._chartsViews[0]._data._graphicEls));//计算节点数量
            let height = 800;//默认高度
            let currentHeight = 30*(nodeList.length-1)||100;//动态高度
            let newHeight = Math.max(currentHeight,height);
            treeDom.style.height= newHeight+"px";
            chartDom.resize();
        }
    });
})
</script>

实现效果

image.png