You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何设置vue3-chartjs图表的固定高度?

Chart.js 支持设置固定高度,你当前配置不生效可通过以下修改解决:

  • 调整图表配置项,关闭默认宽高比限制
    你当前已开启了响应式配置responsive: true,Chart.js 默认会保持图表的宽高比,即使父容器设置了固定高度也不会自动填充,需要新增maintainAspectRatio: false参数关闭该特性,修改后的options片段如下:
options: {
  min: 0,
  max: 100,
  responsive: true,
  // 新增下方配置,关闭宽高比强制保持
  maintainAspectRatio: false,
  plugins: {
    legend: {
      position: "top",
    },
  },
  scales: {
    y: {
      min: -100,
      max: 100,
      ticks: {
        callback: function (value) {
          return `${value}%`;
        },
      },
    },
  },
}
  • 保留外层容器的高度设置即可
    你原有外层div的height: 700px配置无需调整,修改配置项后图表会自动适配父容器的固定高度。

修改后完整代码如下:

<template>
  <h2>Bar Chart</h2>
  <div style="height: 700px">
    <vue3-chart-js v-bind="{ ...barChart }" />
  </div>
</template>

<script>
import Vue3ChartJs from "@j-t-mcc/vue3-chartjs";

export default {
  name: "App",
  components: {
    Vue3ChartJs,
  },
  setup() {
    const barChart = {
      type: "bar",
      options: {
        min: 0,
        max: 100,
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            position: "top",
          },
        },
        scales: {
          y: {
            min: -100,
            max: 100,
            ticks: {
              callback: function (value) {
                return `${value}%`;
              },
            },
          },
        },
      },
      data: {
        labels: ["VueJs", "EmberJs", "ReactJs", "AngularJs"],
        datasets: [
          {
            label: "My First Dataset",
            backgroundColor: ["#1abc9c", "#f1c40f", "#2980b9", "#34495e"],
            data: [40, 20, 50, 10],
          },
          {
            label: "My Second Dataset",
            backgroundColor: ["#2ecc71", "#e67e22", "#9b59b6", "#bdc3c7"],
            data: [-40, -20, -10, -10],
          },
        ],
      },
    };

    return {
      barChart,
    };
  },
};
</script>

内容的提问来源于stack exchange,提问作者Aras121

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 07:57:04