Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c3.js chart doesn't update when loading remote data using vue.js

Currently I have a component using vue and c3. The c3 chart renders immediately, however I am still grabbing the data via ajax. How do I delay the rendering of the component? OR once the data is fetched THEN display the chart.

My code is pretty straighforward.

<my-chart :chartdata="chart.data"></my-chart> etc.

Note: If I enter static data - it renders perfectly.

JSFIDDLE https://jsfiddle.net/1o4kqjwd/3/

like image 436
KingKongFrog Avatar asked Dec 01 '25 14:12

KingKongFrog


1 Answers

First, add a v-if directive to the <my-chart> tag to only render it when the data (mydata, in your fiddle) is loaded:

<my-chart :chartdata="mydata" v-if="mydata"></my-chart>

Second, in the component definition for my-chart, you need to add a watcher to mydata to call the render method (drawChart(), in your fiddle) whenever mydata changes:

watch: {
  mydata() {
    this.drawChart();
  }
},

Finally, you can put the ajax call in its own method on the parent Vue definition. This way, you can call it in the mounted() life-cycle hook and then subsequently from anywhere within that instance's scope:

methods: {
  fetchData() {
    var self = this;  

    this.$http.get('yoururl').then(function(response) {
      let chartData = response.data;

      // do any formatting to chartData here

      self.data = chartData;
    })
  }
}
like image 77
thanksd Avatar answered Dec 04 '25 12:12

thanksd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!