Chart.js with Vue3:update()fails,gives infinite recursion errors

pcww981p  于 11个月前  发布在  Chart.js
关注(0)|答案(1)|浏览(109)

我被**Vue3和优秀的Chart.js**库的问题难倒了。
最初使用数据值创建图表效果很好。但对于此应用程序,图表值必须动态更新。根据Chart.js examples,这与更新图表的数据对象后在图表示例(例如,chart.update())上调用update()方法一样简单。
然而,这似乎完全打破。它不更新,并导致以下警告和错误(与错误描述略有变化,取决于浏览器).
[Vue warn]: Unhandled error during execution of native event handler
Uncaught RangeError: Maximum call stack size exceeded(Chrome)
Uncaught InternalError: too much recursion(Firefox)
我创建了一个超级简单的codesandbox.io示例here来演示这个问题。注意,要查看错误,您必须通过单击codesandbox.io渲染窗口右上角的“预览控制台”按钮来查看控制台窗口。

**有趣的数据点:**Vue3和Chart.js是最新版本。出于好奇,我逐步降级了Chart.js,发现update()开始在email protected(https://stackoverflow.com/cdn-cgi/l/email-protection)工作。

任何帮助将不胜感激。
(我知道vue-chartjs助手 Package 器,但出于多种原因,它不是一个好的选择。

wz1wpwve

wz1wpwve1#

您需要在chartInstance周围添加shallowRef
import { shallowRef } from "vue";
所以这个chartInstance: null,变成了chartInstance: shallowRef(null),

<template>
  <div>
    <canvas ref="chartCanvas"></canvas>
    <button @click="updateChartData">Update Chart Data</button>
  </div>
</template>

<script>
import Chart from "chart.js/auto"; // Import Chart.js
import { shallowRef } from "vue";

export default {
  name: "MyChart",
  data() {
    return {
      chartInstance: shallowRef(null),
      chartData: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [
          {
            label: "# of Votes",
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
              "rgba(255, 99, 132, 0.2)",
              "rgba(54, 162, 235, 0.2)",
              "rgba(255, 206, 86, 0.2)",
              "rgba(75, 192, 192, 0.2)",
              "rgba(153, 102, 255, 0.2)",
              "rgba(255, 159, 64, 0.2)",
            ],
            borderColor: [
              "rgba(255, 99, 132, 1)",
              "rgba(54, 162, 235, 1)",
              "rgba(255, 206, 86, 1)",
              "rgba(75, 192, 192, 1)",
              "rgba(153, 102, 255, 1)",
              "rgba(255, 159, 64, 1)",
            ],
            borderWidth: 1,
          },
        ],
      },
    };
  },
  mounted() {
    this.renderChart();
  },
  methods: {
    renderChart() {
      const ctx = this.$refs.chartCanvas.getContext("2d");

      this.chartInstance = new Chart(ctx, {
        type: "bar",
        data: this.chartData,
        options: {
          // Chart options
        },
      });
    },
    updateChartData() {
      const newData = this.generateRandomData();
      this.chartInstance.data.datasets[0].data = newData;
      this.chartInstance.update();
    },
    generateRandomData() {
      return Array.from({ length: 6 }, () => Math.floor(Math.random() * 20));
    },
  },
};
</script>

字符串
https://codesandbox.io/p/devbox/chart-js-vue3-basic-example-forked-t737cv?file=%2Fsrc%2Fcomponents%2FMyChart.vue%3A17%2C19

相关问题