核心:给图例按钮添加点击事件
myChart.on("legendselectchanged", function (params) {
let selected = {
功率柜: true,
母线柜: false,
充电桩终端: false,
网络柜: false,
};
for (let key in selected) {
if (key !== params.name) {
myChart.setOption({
legend: { selected: { [key]: false } },
});
} else {
myChart.setOption({
legend: { selected: { [params.name]: true } },
});
}
}
});
demo
<template>
<div>
<div id="main" style="width: 600px; height: 400px"></div>
</div>
</template>
<script>
import * as echarts from "echarts";
export default {
name: "HelloWorld",
props: {
msg: String,
},
data() {
return {};
},
mounted() {
this.aa();
},
methods: {
aa() {
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById("main"));
// 指定图表的配置项和数据
var option = {
tooltip: {
trigger: "axis",
},
legend: {
data: ["功率柜", "母线柜", "充电桩终端", "网络柜"],
selected: {
功率柜: true,
母线柜: false,
充电桩终端: false,
网络柜: false,
},
},
xAxis: {
data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
type: "category",
},
yAxis: {},
series: [
{
name: "功率柜",
type: "bar",
data: [120, 132, 101, 134, 90, 230, 210],
},
{
name: "母线柜",
type: "bar",
data: [220, 182, 191, 234, 290, 330, 310],
},
{
name: "充电桩终端",
type: "bar",
data: [150, 232, 201, 154, 190, 330, 410],
},
{
name: "网络柜",
type: "bar",
data: [320, 332, 301, 334, 390, 330, 320],
},
],
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
myChart.on("legendselectchanged", function (params) {
let selected = {
功率柜: true,
母线柜: false,
充电桩终端: false,
网络柜: false,
};
for (let key in selected) {
if (key !== params.name) {
myChart.setOption({
legend: { selected: { [key]: false } },
});
} else {
myChart.setOption({
legend: { selected: { [params.name]: true } },
});
}
}
});
},
},
};
</script>