Bagaimana cara mengkonfigurasikan chart dengan get data dari api menggunakan axios di vue 3

<template>
  <div class="container">
  <div class="card">
    <div class="card-body">
      <h4 class="card-title" style="text-align:center">Chart</h4>
      <hr>
      <MonthlyChart
          v-if="state.isLoaded"
          v-bind:chartData="state.chartData"
          v-bind:chartOptions="state.chartOptions"
      />
    </div>
    </div>
  </div>
</template>

<script>
import { onMounted, reactive } from "vue";
import { useRouter } from "vue-router";
import axios from "axios";
import MonthlyChart from '../../components/Chart'
import { Pie } from "vue3-chart-v2";

export default ({
  name: 'App',
  extends: Pie,
  components: {
    MonthlyChart
  },
  setup () {
    //state token
    const token = localStorage.getItem("token");

    //inisialisasi vue router on Composition API
    const router = useRouter();

    const state = reactive({
        isLoaded: false,
        chartData: {
          datasets: [
            {
              data: [],
            }
          ],
          // These labels appear in the legend and in the tooltips when hovering different arcs
          labels: ""
        },
        chartOptions: {
          responsive: true
        }
      })

   onMounted(() => {
      if (!token) {
        return router.push({
          name: "login",
        });
      }

      state.isLoaded = false
      axios.defaults.headers.common.Authorization = `Bearer ${token}`;
      axios
        .get("http://pkl2021-persuratan.argocipta.com/api/grafik/dashboard")
        .then((response) => {
          //console.log(response.data.name)
          state.value = response.data.data;
          state.chartData.datasets.data= Object.values(state.value);
          state.chartData.labels = Object.getOwnPropertyNames(state.value)
          state.isLoaded = true

          console.log('stateName', Object.getOwnPropertyNames(state.value));
          console.log('stateVal', Object.values(state.value));
          console.log('state: ', state.value);
          console.log('stateData: ', state.chartData.datasets.data);
          console.log('stateLabels: ', state.chartData.labels);
        })

        .catch((error) => {
          console.log(error.response.data);
        });
   })

   return {
     state,
    //  chartData
   };

  },
})
</script>
avatar Mariawid
@Mariawid

1 Kontribusi 0 Poin

Dipost 2 tahun yang lalu

Belum ada Jawaban. Jadi yang pertama Jawaban

Login untuk ikut Jawaban