简体   繁体   English

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

[英]How to update the chart dynamically with vue-chartjs?

I'm using vue.js and vue-chartjs for the first time.我是第一次使用vue.jsvue-chartjs In the simplified code example I want to add a label to the chart by pressing the add Label button, but the chart is not updating.在简化的代码示例中,我想通过按add Label按钮向图表添加标签,但图表没有更新。 My code is based on this tutorial.我的代码基于教程。

I tried calling the render method from the child component, but that does not work.我尝试从子组件调用render方法,但这不起作用。

编辑 Vue Chart.js 添加标签

I expected that when I click the add Label button that the label 13 will be added to the chart.我希望当我单击add Label按钮时,标签13将被添加到图表中。

What helped me was adding a v-if="loaded" , which you will set to false before your change.对我有帮助的是添加了一个v-if="loaded" ,您将在更改之前将其设置为false Then, after your change, set it to false .然后,在您进行更改后,将其设置为false

You have a few mistakes in your code.您的代码中有一些错误。 First if you want to call a method from child component you have to use special attribute ref .首先,如果要从子组件调用方法,则必须使用特殊属性ref Please see more about ref .请参阅有关ref的更多信息。

So in your code it should be:所以在你的代码中应该是:

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

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

Second you have a typo in your Chart.js:其次,您的 Chart.js 中有一个错字:

this.chartData // Not this.chartdata

So this means yours render method in mounted is not working and unnecessary.因此,这意味着您在mounted中的render方法不起作用且不必要。 Your chart is already drawn by reactiveProp after you set chartData prop.设置chartData后,您的图表已由reactiveProp绘制。

But unfortunately this:但不幸的是:

this.datacollection.labels.push(13);

still not work.还是不行。 If you looking at the source code here you will see the library use watcher on chartData only.如果您查看此处的源代码,您将看到该库仅在chartData上使用观察器。 It means if you change entire of chartData this will work fine (as it works at first drawn).这意味着如果您更改整个chartData这将正常工作(因为它在第一次绘制时工作)。 Please see more about watcher .请参阅有关watcher的更多信息。

So if you want to rely on reactiveProp then when you want update labels you should set:所以如果你想依赖reactiveProp那么当你想要更新labels时,你应该设置:

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

编辑 Vue Chart.js 添加标签

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM