如何使用 vue-chartjs 动态更新图表?

How to update the chart dynamically with vue-chartjs?

我是第一次使用 vue.jsvue-chartjs。 在简化的代码示例中,我想通过按 add Label 按钮向图表添加标签,但图表没有更新。我的代码基于 this 教程。

我试过从子组件调用 render 方法,但那不起作用。

我预计当我单击 add Label 按钮时标签 13 将被添加到图表中。

您的代码中有一些错误。首先,如果你想从子组件调用一个方法,你必须使用特殊属性 ref。请查看更多关于 ref.

所以在你的代码中应该是:

<template>
  ...
  <chart ref='chart' :chart-data="datacollection"></chart>
  ...
</template>

<script>
  ...
  this.$refs.chart.render() // Not Chart.render()
  ...
</script>

其次,您的 Chart.js 中有错字:

this.chartData // Not this.chartdata

所以这意味着您在 mounted 中的 render 方法无效且不必要。在您设置 chartData prop.

后,您的图表已经由 reactiveProp 绘制

但不幸的是:

this.datacollection.labels.push(13);

还是不行。如果您查看源代码 here you will see the library use watcher on chartData only. It means if you change entire of chartData this will work fine (as it works at first drawn). Please see more about watcher.

所以如果你想依赖 reactiveProp 那么当你想要更新 labels 你应该设置:

this.datacollection = {
  ...this.datacollection,
  labels: this.datacollection.labels.concat(13) // avoid to mutate data
}

对我有帮助的是添加 v-if="loaded",您将在更改之前将其设置为 false。然后,在您更改之后,将其设置为 false.