在 vue 中显示来自 rapidapi 的 API 数据

Display API data from rapidapi in vue

我正在玩弄 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],没有我期望显示的数据。

我做错了什么?

您应该 define a method in the Vue instance 获取您的 API 数据。

像这样:

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

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

然后您可以像 chuckData: []

一样启动 chuckData

最终解决方案如下所示:

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

谢谢!