在用Vue3封裝 ECharts 的力導向圖(graph
+ force
)時,我遇到一個問題:點擊圖例切換節點顯隱后,線條殘留在原位置,畫布出現“臟線條”。(問題如下:)
這個問題本質上是因為…(我沒找到本質原因,希望有大佬路過能解惑~)
問題復現代碼
<template><div class="echarts-wrap" ref="chartRef"></div>
</template><script setup>
import { onMounted, ref } from "vue";
import * as echarts from "echarts";// dom 元素(容器)
const chartRef = ref(null);
// echarts 實例
const chart = ref(null);
// echarts 配置
const option = {legend: {top: 30,data: ["動力系統", "結構部件"],},series: [{type: "graph",layout: "force",// 讓線條間拉長點,容易看出bugforce: {repulsion: 600,edgeLength: 200,},// 節點大小symbolSize: 50,label: {show: true, // 顯示節點標簽fontSize: 14,},// 強制顯示標簽edgeLabel: {show: true,},categories: [{ name: "動力系統" }, { name: "結構部件" }],// 兩個節點data: [{ id: 1, name: "發動機", value: 15, category: "動力系統" },{ id: 2, name: "機翼", value: 15, category: "結構部件" },],// 一條連線links: [{ source: 0, target: 1 }],},],
};function initChart() {if (!chartRef.value) return;// 初始化 echarts 實例chart.value = echarts.init(chartRef.value);// 使用配置顯示圖譜chart.value.setOption(option);
}onMounted(() => {initChart();
});
</script><style lang="scss" scoped>
.echarts-wrap {width: 500px;height: 500px;padding: 12px;background: #fff;border-radius: 8px;box-shadow: 0 6px 16px rgba(0, 0, 0, 0.06);
}
</style>
注意一:初始化echarts實例的時候不用響應式
// echarts 實例
let chart = null;
// echarts 配置
const option = [/*維持原樣*/]function initChart() {if (!chartRef.value) return;// 初始化 echarts 實例chart = echarts.init(chartRef.value);// 使用配置顯示圖譜chart.setOption(option);
}
注意二:監聽 legendselectchanged
強制重新布局
如果你和我的問題代碼一樣用的響應式,并且不想改成let,那就直接加上下面的代碼
chart.value.on("legendselectchanged", () => {const option = chart.value.getOption();chart.value.clear();chart.value.setOption(option, true);
});
缺點: 節點會到處蛄蛹