【问题标题】:Display API data from rapidapi in vue在 vue 中显示来自 rapidapi 的 API 数据
【发布时间】:2020-04-13 11:02:17
【问题描述】:

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

我做错了什么?

【问题讨论】:

    标签: javascript api vue.js rapidapi


    【解决方案1】:

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

    像这样:

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

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

    然后你可以像chuckData: []一样启动chuckData

    【讨论】:

      【解决方案2】:

      最终的解决方案如下所示:

      <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-02-09
        • 2022-01-21
        • 2018-12-28
        • 2021-10-03
        • 1970-01-01
        • 2021-08-16
        • 2021-07-14
        • 2020-10-14
        • 1970-01-01
        相关资源
        最近更新 更多