Vue3 + ECharts 实战:打造精美的动态柱状图

效果如图:
在这里插入图片描述

完整代码

<template>
  <div class="layout-padding" style="background-color: #d7e9f6;">
    <el-row :gutter="10">
      <el-col :span="9">
        <el-card class="top-card" style="background-color: #f1f6fb;border-radius: 8px;box-shadow: none;height: 120px;">
          <div style="font-weight: bold;margin-left: 10px;margin-top: 10px;">航母数量</div>
          <div style="height: 85px;margin-left: 35px;" ref="chart3"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import * as echarts from 'echarts';

// 用于存储所有 ECharts 实例,方便统一管理
const state_chart = reactive({
  myCharts: [] as echarts.EChartsType[],
});

// 获取图表容器的 DOM 引用
const chart3 = ref<HTMLElement>();

// 初始化图表
const chart3 = ref();
const init_chart3 = async () => {
  const myChart = echarts.init(chart3.value);
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      top: '16%',    
      bottom: '1%',  
      containLabel: true 
    },
    xAxis: [
      {
        type: 'category',
        data: ['中国', '美国', '英国']
      }
    ],
    yAxis: [
      {
        type: 'value',
        splitNumber: 1,
      }
    ],
    series: [
      {
        data: [3, 11, 1],
        type: 'bar',
        itemStyle: {
          color: function (params) {
            const colorList = ['#5470c6', '#91cc75', '#fac858'];
            return colorList[params.dataIndex];
          }
        },
        label: {
          show: true,
          position: 'top'
        }
      }
    ]
  };

  myChart.setOption(option);
  state_chart.myCharts.push(myChart);
};

// 组件挂载后初始化图表
onMounted(() => {
  init_chart3();
});

// 组件卸载前,销毁图表实例,释放内存
onUnmounted(() => {
  state_chart.myCharts.forEach(chart => {
    chart.dispose();
  });
});
</script>

<style scoped lang="scss">
.layout-padding {
  padding: 16px;
}

:deep(.top-card.el-card) {
  --el-card-padding: 0px;
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值