C3.js graph not updating when loading remote data with vue.js
I currently have a component using vue and c3. The c3 graph renders right away, however I am still grabbing the data via ajax. How to defer rendering of a component? OR, once the data has been retrieved, THEN will display the chart.
My code is pretty simple.
<my-chart :chartdata="chart.data"></my-chart> etc.
Note. If I enter static data - it displays fine.
JSFIDDLE https://jsfiddle.net/1o4kqjwd/3/
source to share
First add a directive v-if
to the tag <my-chart>
to only display it when the data is loaded ( mydata
in your fiddle):
<my-chart :chartdata="mydata" v-if="mydata"></my-chart>
Second, in the component definition for, my-chart
you need to add an observer to in mydata
order to call the render method ( drawChart()
, in your fiddle) when it mydata
changes:
watch: {
mydata() {
this.drawChart();
}
},
Finally, you can place the ajax call in your own method in the parent Vue definition. This way you can call it in the mounted()
lifecycle hook and then from anywhere within that instance:
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;
})
}
}
source to share