1👍
I apologize: vuejs documentation on how to fetch async data and integrate it into you application is not the best. I wish they would be more opinionated on best practices here with more examples.
Your problem: A component depending on async data
While your async api call is being made, this.values
is an empty array (this.values.data
doesn’t exist until the api call responds). Before the data comes back, vue creates the child component which creates a chart in it using the empty values array, resulting in a blank chart. You must wait until the data is loaded to create the child component (and hence the chart). So how do we do that?
The solution: Conditional component rendering
- Fetch data in the created hook, not the mounted hook. Reason: asking for data earlier is more performant, see: https://v2.vuejs.org/v2/guide/instance.html
- On data response, save that data into your vue component. Reason: you need that data, see: https://v2.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html#ad
- On save, signal to your html that the data is ready using a variable
this.loaded = true
, and use av-if="loaded"
on any child components that depend on that data, see: https://v2.vuejs.org/v2/guide/conditional.html
Here is a working code sandbox with a dummy api call replicating your changes: https://codesandbox.io/s/vue-template-4b3lm
All of the changes were made to the Chartjs.vue file.
Some other errors I saw you make:
- Declaring variables in the component section
- Setting this.values too many times in too many places. Just declare it once in data and set it later as needed.
Some other ways you could solve this:
- Use a watcher in the child components instead of
v-if
: to re-render the chart inside the component (instead of delaying the whole component with v-if) when the data comes in (any time the props change). - Use vuex