0

我正在玩 vueJS 和 rapidapi,我正在尝试使用 vue 显示来自 API 的数据并使用 JS Fetch 方法检索 API。但是,当我运行代码时,我得到的只是启动它的值(即:[])。

<template>
  <div>
    <div>{{ chuckData }}</div>
  </div>
</template>

<script>
var chuck = [];
fetch("https://matchilling-chuck-norris-jokes-v1.p.rapidapi.com/jokes/random", {
  method: "GET",
  headers: {
    "x-rapidapi-host": "matchilling-chuck-norris-jokes-v1.p.rapidapi.com",
    "x-rapidapi-key": "***"
  }
})
  .then(response => response.json()) // Getting the actual response data
  .then(data => {
    chuck = data;
  })
  .catch(err => {
    console.log(err);
  });

export default {
  data() {
    return {
      chuckData: chuck
    };
  }
};
</script>

我还尝试使用以下内容:

var chuck fetch("https://matchilling-chuck-norris-jokes-v1.p.rapidapi.com/jokes/random", {...}

但我得到的只是 [object Promise] 没有我期望显示的数据。

我究竟做错了什么?

4

2 回答 2

1

你应该在 Vue 实例中定义一个方法来获取你的 API 数据。

像这样:

methods: {
    getRapidApiData() {
        //do the fetch.... etc
    }
}

您可以摆脱它,var chuck = [];因为它不需要并替换chuckwith的引用this.chuckData

然后你可以像这样启动chuckDatachuckData: []

于 2020-04-13T11:32:54.857 回答
0

最终解决方案如下所示:

<div class="col-md-3" v-for="result in chuck">
         {{result}}
</div>

<script>
export default {
  data() {
    return {
      chuck: []
    };
  },
  mounted() {
    this.getData();
  },
  methods: {
    getData() {
    fetch("https://matchilling-chuck-norris-jokes-v1.p.rapidapi.com/jokes/random", {
      method: "GET",
      headers: {
        "x-rapidapi-host": "matchilling-chuck-norris-jokes-v1.p.rapidapi.com",
        "x-rapidapi-key": "<API KEY>"
      }
    })
      .then(response => response.json())
      .then(data => {
        this.chuck = data;
      });
    }
  }
};
</script>

谢谢!

于 2020-04-14T07:20:03.120 回答