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

标签 javascript api vue.js rapidapi

我正在使用 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: []

关于javascript - 在vue中显示来自rapidapi的API数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61186461/

相关文章:

javascript - 如何模拟点击事件

objective-c - Twitter API 的签名是如何真正起作用的?

javascript - 什么时候需要 Google Maps API key ?

javascript - 在 Vuejs 中为 v-for 创建的元素添加方法

javascript - vue js动态重新排列组件的子组件

javascript - .focus() "set focus on a target input"在 Firefox 中不起作用

javascript - 使用 Date 对象的组件在不同的时区产生不同的快照

javascript - jQuery 从隐藏输入字段获取默认值

api - 我们可以在 Paypal REST API 中使用引用交易吗?

unit-testing - 如何测试vue Js metaInfo