How can i call a Rest API from a Vue component?

Viewed 6083

I'm just getting started to VueJS and i'm trying to create a very simple page where a pie chart with some data is shown.

Right now, i managed to display the chart using example data, but now i would like to populate the chart with data retrieved from an api call on my backend http://127.0.0.1:8000/user/getamount.

Here is my code:

chart.js

import Vue from "vue/dist/vue.js";
import Vuex from "vuex";
import storePlugin from "./vuex/vuex_store_as_plugin";
import App from './App.vue'
import HighchartsVue from "highcharts-vue";
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(Vuex);
Vue.use(storePlugin);
Vue.config.productionTip = false;
Vue.use(HighchartsVue);
Vue.use(VueAxios, axios)


new Vue({
  el: "#app",
  render: h => h(App),
});

App.vue

<template>
  <div>
    <highcharts class="hc" :options="chartOptions" ref="chart"></highcharts>
  </div>
</template>

<script>

export default {
  data() {
    return {
      chartOptions: {
        series: [{

           type: 'pie',
           name: 'Browser share',
           data: [
              ['Firefox',   45.0],
              ['IE',       76.8],
              ['Safari',    8.5],
              ['Opera',     6.2],
              ['Others',   0.7]
           ]
        }],

      }
    };
  }
};
</script>

I just got to started to Vue so a lot of stuff is not clear yet, but where am i supposed to perform the API request here? I've seen a lot of examples where axios is used to call an API and show data on the page, but in this case i need data on my component, since the chart it's there. Should i just perform the call from the component? Or am i missing something? Any kind of advice is appreciated

3 Answers

Since you will still load data, define it but start the variable null:

series: [{
   type: 'pie',
   name: 'Browser share',
   data: null
}],

In created (marked as async for async/await pattern), load the data using axios:

import axios from 'axios';
export default {
  data() {
  ...
  },
  async created() {
    const response = await axios.get(...);  // Load the data from your api url
    this.chartOptions.series[0].data = response.data;  // set the data
    // `response.data` should contain:
    /*
      [
        ['Firefox',   45.0],
        ['IE',       76.8],
        ['Safari',    8.5],
        ['Opera',     6.2],
        ['Others',   0.7]
      ]
    */
  }
}

Here's a sandbox simulating this with a setTimeout

import axios from 'axios';

 data () {
  return {
    getAmount: []
  }
  },
  methods: {
    fetch() {
        axios.get('https://127.0.0.1:8000/user/getamount')
      .then((response) => {
        this.getAmount = response.data;
      })
    }
  },
  mounted() {
  this.fetch();
  }
})

If you want to display it in html, then you make a loop.

<div v-for="amount in getAmount" :key="amount.id">
{{amount}}
</div>

You can just define a function in your new component that needs the data on load. So yes, in case of your chart component you could make a Axios request there. So then the script part would look like this.

<script>
import axios from 'axios';

    export default {
      data () {
        return {
          graph_data: [],
        }
      },
      created () {
        this.fetchGraphData()
      },

      methods: {
        fetchGraphData() {
           axios.get('your_address')
             .then(function (response) {
               //Fill your data here
             })
        }
     }
</script>
Related