简体   繁体   中英

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.

编辑 Vue Chart.js 添加标签

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

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 .

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
}

编辑 Vue Chart.js 添加标签

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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