vue3 echarts 通过点击按钮 隐藏相应项

<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 // 图例默认显示,设为 false 仍可切换
    },
    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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值