簡體   English   中英

如何從 Vue 組件調用 Rest API?

[英]How can i call a Rest API from a Vue component?

我剛剛開始使用 VueJS,我正在嘗試創建一個非常簡單的頁面,其中顯示了帶有一些數據的餅圖。

現在,我設法使用示例數據顯示圖表,但現在我想用從我的后端http://127.0.0.1:8000/user/getamount上的 api 調用檢索到的數據填充圖表。

這是我的代碼:

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),
});

應用程序.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>

我剛開始使用 Vue,所以很多東西還不清楚,但是我應該在哪里執行 API 請求? 我見過很多例子,其中 axios 用於調用 API 並在頁面上顯示數據,但在這種情況下,我需要組件上的數據,因為圖表就在那里。 我應該只執行來自組件的調用嗎? 還是我錯過了什么? 任何形式的建議表示贊賞

由於您仍將加載數據,因此定義它但啟動變量null

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

created (標記為async for async/await 模式)中,使用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]
      ]
    */
  }
}

這是一個用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();
  }
})

如果你想在 html 中顯示它,那么你做一個循環。

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

您只需在需要加載數據的新組件中定義 function 即可。 所以是的,如果是您的圖表組件,您可以在那里提出 Axios 請求。 所以腳本部分看起來像這樣。

<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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM