在用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);
});
缺点: 节点会到处蛄蛹