3

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/

12
  • Presuming the ajax call returns a promise, initialize c3 in a then. Commented May 2, 2017 at 22:57
  • How do I initialize it after the ajax call IF the logic to generate it is in the component? Commented May 2, 2017 at 22:58
  • Do the ajax call the a lifecycle event like mounted or created. If this is the same thing as your next to last question, in mounted, make the ajax and initialize c3 in the callback. Commented May 2, 2017 at 23:01
  • Can't you just do <my-chart v-if="chart.data" :chartdata="chart.data"></my-chart>? Commented May 3, 2017 at 0:43
  • @thanksd good idea. However if I want to pulse the API and update the chart that wouldn't work. Commented May 3, 2017 at 1:43

1 Answer 1

4

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;
    })
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I think the name of the property is watch, not watchers: watch: { mydata: () => {...}}
You're right that was a typo. Thanks! And you maybe weren't suggesting this, but just fyi that you shouldn't use an arrow function in this case because you'll lose the context of this. See stackoverflow.com/questions/43929650/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.