Trigger/call function when component is rendered?
-
Is there a way to once call a function when as soon as a component is rendered - so to say a kind of @click but in the sense of @loaded?
I use Apexcharts and fetch data via Axios. I call the function to get the data inside mounted() and also use $nextTick.
mounted() { this.$nextTick(function() { this.getProjectAnalysis(); // this calls function with Axios getting the data });
But from time to time the Apex component seems not ready cause updating the data with updateOptions() runs into an error. Console says “Cannot read property ‘updateOptions’ of undefined”.
Maybe someone has an idea for a workaround?
-
@dirkhd Apexcharts seems to have its own mounted event: https://apexcharts.com/docs/options/chart/events/
Some more information on how you integrate Apex, but assuming you’re using the vue component, something like this maybe?
<template> <div> <apexchart width="500" type="bar" :options="options" :series="series"></apexchart> </div> </template> <script> export default { data() { return { options: { chart: { events: { mounted: (chartContext, config) => { this.getProjectAnalysis() } } } } } } } </script>
Completely untested, just what I would try from looking at the docs
-
@beets You are awesome
It works and in addition this also solved my second problem. Because when you use Apex inside tabs then the chart disappears (at least the part with the data, not the legend) in case you switch between the tabs. But no the chart is “refilled” with the data because the function is called again.
-
@dirkhd Great, glad I could help. It wasn’t entirely obvious from the docs alone, I also took a look at the vue component source code here: https://github.com/apexcharts/vue-apexcharts/blob/master/src/ApexCharts.component.js
So just as a reference, you can add anything from the options API here: https://apexcharts.com/docs/options/annotations/ (I just linked to annotations page, but any other would work.