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

如何让ApexCharts实时更新Firestore监听器获取的数据?

解决Vue中ApexCharts实时数据不更新的问题

问题根源分析

你的代码中存在两个核心问题导致图表无法自动更新:

  1. 父组件处理日期数据时,使用push修改原数组,数组引用未发生变化,子组件无法感知到数据更新
  2. 子组件的options和series仅在初始化时赋值一次,未监听props的变化,无法响应数据更新

步骤1:修复父组件的数据处理逻辑

修改父组件中监听getWeight的代码,确保每次数据更新时生成新的数组,让Vue的响应式系统能检测到变化:

watch(
  () => props.getWeight,
  (getWeights) => {
    // 直接重新赋值weight数组,确保引用更新
    weight.value = [...getWeights.weightData.weight];

    const numeric = { day: "numeric", month: "numeric" };
    // 使用map生成新的日期数组,替代push操作
    date.value = getWeights.weightData.date.map(dates => 
      dates.toDate().toLocaleDateString("se-SW", numeric)
    );
  },
  { immediate: true } // 确保组件挂载时立即执行一次初始化
);

步骤2:让子组件响应props变化

有两种方案可以实现图表的自动更新,任选其一即可:

方案一:使用计算属性(推荐)

通过Vue的computed属性动态生成图表配置,当props变化时自动更新:

<template>
  <apexchart class="apexchart" type="line" :options="chartOptions" :series="chartSeries" />
</template>

<script>
import { computed } from 'vue';

export default {
  props: ["weight", "date"],
  setup(props) {
    // 响应式生成图表配置
    const chartOptions = computed(() => ({
      xaxis: {
        type: "category",
        categories: props.date,
        axisBorder: {
          show: false,
        },
      },
    }));

    // 响应式生成数据系列
    const chartSeries = computed(() => ([
      {
        name: "Værdi",
        data: props.weight,
      },
    ]));

    return {
      chartOptions,
      chartSeries
    };
  },
};
</script>

方案二:手动监听props并更新图表实例

如果方案一不生效,可以直接获取图表实例,手动触发更新:

<template>
  <apexchart ref="chartRef" class="apexchart" type="line" :options="options" :series="series" />
</template>

<script>
import { ref, watch } from 'vue';

export default {
  props: ["weight", "date"],
  setup(props) {
    const chartRef = ref(null);
    const options = ref({
      xaxis: {
        type: "category",
        categories: props.date,
        axisBorder: {
          show: false,
        },
      },
    });
    const series = ref([
      {
        name: "Værdi",
        data: props.weight,
      },
    ]);

    // 监听props变化,手动更新图表
    watch([() => props.weight, () => props.date], ([newWeight, newDate]) => {
      series.value[0].data = newWeight;
      options.value.xaxis.categories = newDate;
      
      if (chartRef.value) {
        chartRef.value.updateOptions(options.value);
        chartRef.value.updateSeries(series.value);
      }
    }, { deep: true, immediate: true });

    return {
      chartRef,
      options,
      series
    };
  },
};
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 01:45:38