【问题标题】:How can i call a Rest API from a Vue component?如何从 Vue 组件调用 Rest API?
【发布时间】:2020-12-20 14:16:51
【问题描述】:

我刚刚开始使用 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),
});

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 并在页面上显示数据,但在这种情况下,我需要组件上的数据,因为图表就在那里。我应该只执行来自组件的调用吗?还是我错过了什么?任何形式的建议表示赞赏

【问题讨论】:

  • 在您的 data() 旁边添加一个像 mounted() {} 这样的钩子以在其中进行 API 调用

标签: javascript vue.js highcharts vuejs2 vue-component


【解决方案1】:

由于您仍将加载数据,请定义它但启动变量null

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

created(标记为async 用于异步/等待模式)中,使用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]
      ]
    */
  }
}

这是一个 sandboxsetTimeout 模拟这个

【讨论】:

  • 非常感谢!这似乎是最好的解决方案
【解决方案2】:
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>

【讨论】:

    【解决方案3】:

    您可以在新组件中定义一个需要加载数据的函数。所以是的,如果是您的图表组件,您可以在那里发出 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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-27
      • 2017-05-07
      • 1970-01-01
      • 2022-07-15
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 2020-03-04
      相关资源
      最近更新 更多