1.methods初始化树状图方法并根据节点动态设置容器高度
// 根节点的背景图
import gen from '@/assets/fiveImg/d-gen.png'
// 子节点的背景图
import zi from '@/assets/fiveImg/d-zi.png'
// 根据子节点个数动态设置容器高度
dynamicHeight() {
let container = this.$refs.tree
let allNode = 0
let nodes = this.myChart._chartsViews[0]._data._graphicEls
for (let i = 0, count = nodes.length; i < count; i++) {
let node = nodes[i]
if (node === undefined) continue
allNode++
}
// 根据子项目多少决定高度
let height = window.innerHeight
let currentHeight = 65 * allNode
let newHeight = Math.max(currentHeight, height)
container.style.height = newHeight + 'px'
if (nodes.length <= 5) {
container.style.height = '430px'
} else {
// 超过5个根据节点宽度*个数,设置容器宽度
container.style.height = newHeight + 'px'
}
this.myChart.resize()
},
// 树
initThree(data) {
const option = {
tooltip: { formatter: (params) => params.data.name },
toolbox: {
feature: {
saveAsImage: { title: '',
name: '指标分类',
iconStyle: { borderColor: "#666" },
emphasis: {iconStyle: { borderColor: "#666"}},
},
}
},
series: {
type: 'tree',
symbolSize: ['180', 80],
left: 120,
right: 120,
top: 0,
bottom: 0,
initialTreeDepth: 4, //展示的层数(从0开始)
symbol: `image://${zi}`,
edgeShape: 'polyline',
label: {
position: ['50%', '20%'],
align: 'center',
color: '#570100',
formatter: ({ data }) => {
if (data.name.length > 8) {
return `{name|${data.valueCalc}(分)}\n${(data.name && data.name.slice(0, 8) + '...') || ''}`
} else {
return `{name|${data.valueCalc}(分)}\n${data.name || ''}`
}
},
rich: { name: { fontWeight: 700, fontSize: 20, padding: [0, 0, 10, 0] } },
},
lineStyle: { color: '#E8672B' },
// ...data[0]展示数据,因为需要对象格式,而后端返回了数组所以我取了第一个
/**
数据格式:children可以无线嵌套
{name:'显示文字',children:[{name:'显示文字'}]}
*/
data: [{ symbolSize: [188, 80], symbol: `image://${gen}`, ...data[0] }],
},
}
this.myChart = echarts.init(this.$refs.tree)
this.myChart.setOption(option)
// 初始化计算容器高度
this.dynamicHeight()
// 点击节点展开收起重新计算高度
this.myChart.on('click', () => this.dynamicHeight())
},
2.效果