菜鸟-创作你的创作

Vue3绘制多系列柱状图与曲线图的示例代码

下面给你 Vue 3 + ECharts 实现 多系列柱状图(Bar)+ 曲线图(Line) 的完整示例代码,直接可用,适合前端项目中快速集成。


✅ Vue3 绘制多系列柱状图与曲线图(Bar + Line)示例代码

使用 ECharts 5 + Vue 3 Composition API


📌 1. 安装 ECharts

npm install echarts


📌 2. 创建组件(BarLineChart.vue)

下面代码结构清晰、可直接运行,含响应式大小、悬停提示、坐标轴、双轴处理等。

<template>
  <div ref="chartRef" style="width:100%; height:400px;"></div>
</template>

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

const chartRef = ref<HTMLElement | null>(null);
let chartInstance: echarts.ECharts | null = null;

onMounted(() => {
  if (!chartRef.value) return;

  chartInstance = echarts.init(chartRef.value);

  const option = {
    title: {
      text: "多系列柱状图 + 曲线图",
      left: "center"
    },
    tooltip: {
      trigger: "axis"
    },
    legend: {
      top: "5%",
      data: ["销售额", "利润", "增长率"]
    },
    xAxis: {
      type: "category",
      data: ["1月", "2月", "3月", "4月", "5月", "6月"],
    },
    yAxis: [
      {
        type: "value",
        name: "金额(万元)"
      },
      {
        type: "value",
        name: "增长率(%)",
        position: "right",
        axisLine: {
          show: true
        }
      }
    ],
    series: [
      // 柱状图系列1
      {
        name: "销售额",
        type: "bar",
        data: [120, 200, 150, 80, 70, 110],
        barWidth: 30
      },
      // 柱状图系列2
      {
        name: "利润",
        type: "bar",
        data: [20, 40, 25, 18, 15, 28],
        barWidth: 30
      },
      // 折线图系列(右侧 Y 轴)
      {
        name: "增长率",
        type: "line",
        yAxisIndex: 1,
        data: [2, 5, 3, 1, 0.5, 2.5],
        smooth: true
      }
    ]
  };

  chartInstance.setOption(option);

  // 监听窗口变化自动缩放
  window.addEventListener("resize", resizeChart);
});

const resizeChart = () => {
  chartInstance?.resize();
};

onBeforeUnmount(() => {
  window.removeEventListener("resize", resizeChart);
  chartInstance?.dispose();
});
</script>

<style scoped>
/* 可根据需求设置组件样式 */
</style>


🎯 代码亮点解析

✔ 同时支持柱状图 + 折线图

type: "bar"type: "line" 混合使用。

✔ 双 Y 轴

适用于金额与百分比等不同量纲:

yAxis: [
  {...}, // 金额
  {...}  // 增长率
]

✔ 响应式自适应大小

window.addEventListener("resize", resizeChart);

✔ 平滑折线图

smooth: true


📌 如何在页面中使用?

<template>
  <BarLineChart/>
</template>

<script setup>
import BarLineChart from "./components/BarLineChart.vue";
</script>

你想要哪个版本?

退出移动版