API 数据显示在浏览器的控制台中,但未显示在网页上 - Vue.js

API data is showing in the browser's console but not on the webpage - Vue.js

我是 API 设计的新手,我正在尝试实现一个 API 调用,它只显示来自我使用 vue.js 在网上找到的 API 服务器的数据通过 CLI 项目。虽然我能够在浏览器的控制台中看到结果,但我无法在我正在处理的网页上看到实际数据显示。我见过类似我的问题,但其中 none 似乎和我有同样的问题,使用 Vue。经过几天的研究,我似乎找不到问题所在,而且我很确定这是我搞砸的一个非常基本的事情,这让承认失败更加令人沮丧。这是有问题的代码:

<template>
  <div class="health">
    <p>{{response}}</p>
  </div>
</template>
<script>
import axios from "axios";
export default {
  name: "HelloHealth",
  data() {
    return {
      response: ""
    };
  },
  mounted() {
    axios({
      method: "GET",
      url:
        "https://matchilling-chuck-norris-jokes-v1.p.rapidapi.com/jokes/random",
      headers: {
        "content-type": "application/octet-stream",
        "x-rapidapi-host": "matchilling-chuck-norris-jokes-v1.p.rapidapi.com",
        "x-rapidapi-key": "5788793819msh9c9b16c2298d826p1e5fefjsn3d5bde507db6",
        accept: "application/json"
      }
    })
      .then(response => {
        console.log(response.data);
      })
      .catch(error => {
        console.log(error);
      });
  }
};
</script>

以下是我在控制台中获得的代码结果:

谁能找出我做错了什么?非常感谢。

您没有将 this.response 设置为 "" 以外的任何值。 在你的mounted()调用中,axios调用成功后,你需要设置响应:

 .then(response => {
     this.response = response.data;
 })

Vue 的文档在此处提供了关于使用 API 和将数据集成到 Vue 中的非常好的指南:https://vuejs.org/v2/cookbook/using-axios-to-consume-apis.html

您尚未在您的 response 数据 属性 中设置任何 response 数据。您可以在 mounted() 的方法中调用此 API,而不是直接在 mounted() 中调用 API。这是很好的编码。确切地说,它是如何工作的:

import axios from "axios";
export default {
  data() {
    return {
      response: ""
    }
  },
  methods: {
    getResponseData() {
      axios({
        method: "GET",
        url:
          "https://matchilling-chuck-norris-jokes-v1.p.rapidapi.com/jokes/random",
        headers: {
          "content-type": "application/octet-stream",
          "x-rapidapi-host": "matchilling-chuck-norris-jokes-v1.p.rapidapi.com",
          "x-rapidapi-key": "5788793819msh9c9b16c2298d826p1e5fefjsn3d5bde507db6",
          accept: "application/json"
        }
      })
        .then(response => {
          this.response = response.data;
          console.log(this.response); //get response data
        })
        .catch(error => {
          console.log(error);
        });
      }
  },

  mounted() {
    this.getResponseData();
  }
}

谢谢。

.then(response => {
      this.response = response.data;
      console.log(this.response); //get response data
    })

axios 返回的响应具有不同的范围。 它仅在 then 函数中可用。 您应该将组件的响应设置为axios返回的响应。