Search code examples
vue.jsvuexvuejs3apexchartsvuex4

How to correctly pass array with data to a chart from the VueApexCharts library in vue3?


I am writing a small covid project and trying to plot confirmed infection data using ApexCharts, but the graph is not showing. I enter the data from vuex in two tables. The data is valid however it comes from api and sa in the proxy object. What am I doing wrong? (I am using ApexCharts because vue Chartjs is not compatible with vue 3).

<template>
  <apexchart width="500" type="bar" :options="options" :series="series"></apexchart>
</template>

<script>
import VueApexCharts from "vue3-apexcharts";

export default {
  components: {
    apexchart: VueApexCharts,
  },
 data(){  
   return {
     series: [],
      options: {
        chart: {
          type: "bar",
          height: 400,
          stacked: true
        },
        plotOptions: {
          bar: {
            horizontal: false
          }
        },
        dataLabels: {
          enabled: false
        },
        tooltip: {
          shared: true,
          followCursor: true
        },
        stroke: {
          width: 1,
          colors: ["#fff"]
        },
        fill: {
          opacity: 1
        },
        legend: {
          position: "top",
          horizontalAlign: "center",
          offsetX: 40
        },
        colors: ["rgb(95, 193, 215)", "rgb(226, 37, 43)", "rgb(94, 181, 89)"]
      }
    };
 },
 computed: {
   getDate(){
     return this.$store.getters['chart/getDate'];
   },
   getConfirmed(){
    return this.$store.getters['chart/getConfirmed'];
   }
 },
   methods: {
    fillDate(){
       this.options = {
         xaxis: {
           categories: this.getDate
         }
       }
        this.series = [
         {
           name: 'Confirmed',
           data: this.getConfirmed
         }
       ];
     }
   },
  async mounted() {
    await this.fillDate();
  }
}

The data from the vuex store are two arrays.

Proxy
[[Handler]]: Object
[[Target]]: Array(45)
[[IsRevoked]]: false

Solution

  • Instead of using mounted hook and method try to watch the computed properties then update the data based on that ones:

     computed: {
       getDate(){
         return this.$store.getters['chart/getDate'];
       },
       getConfirmed(){
        return this.$store.getters['chart/getConfirmed'];
       }
     },
    watch:{
       getDate:{
      handler(newVal){
        this.options = {
             xaxis: {
               categories: this.getDate
             }
           },
       deep:true
        },
     getConfirmed:{
       handler(newVal){
        this.series = [
             {
               name: 'Confirmed',
               data: this.getConfirmed
             }
           ];
     },
      deep:true
     }
    }