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

Vue3组合式API中ApexCharts设置y值为0时报错问题排查

问题

在Vue3组合式API环境中使用ApexCharts,通过响应式变量动态配置图表系列数据时遇到异常:

  • 当系列数据为[{ x: '2022-03', y: 2 }]时,图表正常显示
  • 当系列数据为[{ x: '2022-03', y: 0 }]时,抛出错误:Uncaught TypeError: Cannot read properties of undefined (reading '0')
  • 只要系列中存在至少一个y值不为0的元素,图表就能正常运行;所有y值为0时触发报错

相关代码示例:

<template>
  ...
  <apexchart width="100%" height="400" type="bar" :options="orderOptions" :series="orderSeries" ref="orderChart"></apexchart>
  ...
</template>

<script setup>
...
const orderSeries = ref([
  {
    name: 'Orders',
    data: []
  }
]);

const orderOptions = ref({
  xaxis: {
    type: 'datetime'
  },
  yaxis: {
    min: 0,
    labels: {
      formatter: val => val.toFixed(0)
    }
  },
  dataLabels: {
    enabled: false
  },
  markers: {
    size: 7,
    hover: {
      size: 10
    }
  },
  plotOptions: {
    bar: {
      borderRadius: 4,
      borderRadiusApplication: 'end',
      columnWidth: '90%'
    }
  },
  title: {
    text: 'Orders',
    style: {
      fontSize: '20px'
    }
  }
});
...
</script>

解决方案

1. 修复y轴标签格式化函数

报错核心原因是所有y值为0时,ApexCharts内部计算y轴刻度出现异常,导致formatter函数接收的val为undefined。给格式化函数增加空值判断:

yaxis: {
  min: 0,
  labels: {
    formatter: val => (val !== undefined ? val.toFixed(0) : '0')
  }
},

2. 手动设置y轴最大值

强制给y轴设置一个大于0的max值,避免ApexCharts自动计算刻度时出错:

yaxis: {
  min: 0,
  max: 1, // 可根据业务场景调整为合适数值
  labels: {
    formatter: val => val.toFixed(0)
  }
},

3. 数据兜底处理

如果业务允许,当所有y值为0时,给数据数组添加一个极小值的临时数据(比如y: 0.0001),规避空刻度计算问题:

// 示例:更新数据的处理函数
const updateSeriesData = (newData) => {
  const allZero = newData.every(item => item.y === 0);
  orderSeries.value[0].data = allZero ? [...newData, { x: '', y: 0.0001 }] : newData;
};

4. 手动触发图表重绘

更新数据后调用图表的updateOptions方法,强制重新计算渲染逻辑:

import { ref, nextTick } from 'vue';

const orderChart = ref(null);

const updateSeriesData = async (newData) => {
  orderSeries.value[0].data = newData;
  await nextTick();
  if (orderChart.value) {
    orderChart.value.updateOptions(orderOptions.value, {
      redrawPaths: true,
      animate: false
    });
  }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 15:55:16