MatMis
MatMis

Reputation: 319

How to update the chart dynamically with vue-chartjs?

I'm using vue.js and vue-chartjs for the first time. 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. My code is based on this tutorial.

I tried calling the render method from the child component, but that does not work.

Edit Vue Chart.js add label

I expected that when I click the add Label button that the label 13 will be added to the chart.

Upvotes: 1

Views: 10708

Answers (2)

User 28
User 28

Reputation: 5158

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. Please see more about 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:

this.chartData // Not this.chartdata

So this means yours render method in mounted is not working and unnecessary. Your chart is already drawn by reactiveProp after you set chartData prop.

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. It means if you change entire of chartData this will work fine (as it works at first drawn). Please see more about watcher.

So if you want to rely on reactiveProp then when you want update labels you should set:

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

Edit Vue Chart.js add label

Upvotes: 1

Sascha
Sascha

Reputation: 71

What helped me was adding a v-if="loaded", which you will set to false before your change. Then, after your change, set it to false.

Upvotes: 4

Related Questions