<template>
<div>
<!-- 图表容器 -->
<div ref="chartRef" style="width: 600px; height: 400px;"></div>
<!-- 控制按钮 -->
<button @click="toggleSeries('系列A')">切换系列A</button>
<button @click="toggleSeries('系列B')">切换系列B</button>
<button @click="toggleSeries('系列C')">切换系列C</button>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';
const chartRef = ref(null);
const chartInstance = ref(null);
onMounted(() => {
chartInstance.value = echarts.init(chartRef.value);
const option = {
legend: {
data: ['系列A', '系列B', '系列C'],
show: true
},
xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] },
yAxis: { type: 'value' },
series: [
{ name: '系列A', type: 'bar', data: [120, 200, 150, 80, 70, 110, 130] },
{ name: '系列B', type: 'bar', data: [80, 150, 100, 60, 90, 70, 100] },
{ name: '系列C', type: 'bar', data: [200, 180, 160, 140, 120, 100, 80] }
]
};
chartInstance.value.setOption(option);
});
const toggleSeries = (name) => {
if (chartInstance.value) {
chartInstance.value.dispatchAction({
type: 'legendToggleSelect',
name
});
}
};
</script>