如何将数据加载到Vue组件

时间:2019-12-23 20:04:09

标签: vue.js vuejs2 vue-component fetch-api

我在本地主机上有一个https的API端点,该端点提供原始json数据,如下所示:

[{"day":"Monday","hours":43,"date":"2019-12-23T14:38:08.2112312-05:00"},{"day":"Tuesday","hours":36,"date":"2019-12-24T14:38:08.2130238-05:00"},{"day":"Wednesday","hours":39,"date":"2019-12-25T14:38:08.2130318-05:00"},{"day":"Thursday","hours":34,"date":"2019-12-26T14:38:08.2130329-05:00"},{"day":"Friday","hours":42,"date":"2019-12-27T14:38:08.2130338-05:00"}]

我不明白的是,为什么VUE.js失败并出现"TypeError: "NetworkError when attempting to fetch resource." JSON,供本地主机使用,并且启用了cors。任何来自邮递员,浏览器,curl等的获取请求都可以正常工作。只有在VUE.js调用fetch()时才会失败。

VUE组件:

<template>
  <div class="container">
    <LineChart v-if="loaded" :chartdata="chartdata" :options="options" />
  </div>
</template>

<script>
import LineChart from './LineChart.vue';

export default {
  name: 'LineChartContainer',
  components: { LineChart },
  data: () => ({
    loaded: false,
    chartdata: null,
  }),
  async mounted() {
    this.loaded = false;
    try {
      const { daysWorked } = await fetch(
        'https://localhost:5001/api/timeworked',
      );
      console.log('days worked data:', daysWorked);
      this.chartdata = daysWorked;
      this.loaded = true;
    } catch (e) {
      console.error("Couldn't access data:", e);
    }
  },
};
</script>

感谢任何想法,建议或技巧!

1 个答案:

答案 0 :(得分:1)

Vue没问题。您获取的方式有问题。

看看https://developer.mozilla.org/en-US/docs/Web/API/Fetch_APIhttps://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

尝试

...
const { daysWorked } = await fetch('https://localhost:5001/api/timeworked')
                                 .then(r=>r.json());
...

这应该有帮助。