先看效果
具体实现代码如下:
<template>
<div ref="ecs" id="ecs" style="width: 800px;height:800px; background-color:white;"></div>
</template><script setup>
import {onMounted, ref} from "vue";
import * as echarts from 'echarts';const ecs = ref()
const myChart = ref()
const timestamp = ()=>{const dateTimestamp = new Date().getTime();return dateTimestamp+""
}
const my_data = ref({name: "根节点",url: "",id: timestamp(),// 根节点样式设置itemStyle: {color: "#a53626",borderColor: "#a53626",},children: [],}
)
const option = ref({tooltip: {trigger: "item",// 给tooltip绑定click事件triggerOn: "click",enterable: true,extraCssText: 'z-index: 99;max-width: 100px;white-space:pre-wrap',formatter: function(params) {return `<div οnclick="myDialog('${params.data.id}')">添加子节点</div>`},backgroundColor: "#dfdfdf",textStyle: {color: "black",},},series: [{type: "tree",expandAll: true,symbolSize: 75,symbol: "roundRect",edgeShape: "polyline",edgeForkPosition: "50%",initialTreeDepth: 10,orient: "vertical",itemStyle: {color: "black",borderColor: "black",},expandAndCollapse: true,animationDuration: 550,animationDurationUpdate: 750,lineStyle: {color: "#7b7b7b",width: 3,},label: {show: true,position: "insideTop",width: 90,height: 90,textStyle: {fontSize:15,color: "#ff0000",},},data: [my_data.value,],},],
});function nodeContainsValue(node, id, i=0) {i =i+1if (node.id == id) {node.children.push({name: `第${i}级节点`,url: "",id: timestamp(),// 根节点样式设置itemStyle: {color: "#a53626",borderColor: "#a53626",},children: [],})return true;}if (node.children.length == 0) {return false;}for(let j=0; j< node.children.length; j++){if(nodeContainsValue(node.children[j], id, i)){return true}}return false
}
onMounted(() => {timestamp()myChart.value = echarts.init(ecs.value);myChart.value.setOption(option.value);window.myDialog= function(id) {nodeContainsValue(my_data.value, id, 0)myChart.value.setOption(option.value);}
})
</script><style >
html, body{height: 100%;background-color: pink;
}
</style>
环境、版本信息
"dependencies": {"echarts": "^5.5.1","vue": "^3.5.13"},