簡體   English   中英

使用 API 通過 Vue.js 獲取數據時沒有響應或錯誤

[英]No response or error when fetching data with Vue.js using API

我剛開始學習 vue.js 需要一些幫助。 輸入問題時,我正在嘗試使用 API 從外部來源獲取答案。但我沒有得到任何響應,控制台中也沒有錯誤。 我確定錯誤可能是什么。

這是我的代碼https://codesandbox.io/embed/vue-template-dk71y的鏈接

你快到了:) 你只需要修復代碼中的一些問題。

  1. 由於一切都發生在您的Hello World組件中,因此無需嘗試使用道具在其中傳遞questionanswer 只需將所有邏輯放入組件中即可。

  2. 使用v-model指令(雙向綁定)將question綁定到input ,例如: <input v-model="question">

  3. 您應該在watcher內部調用 this.getAnswer()

  4. 並且data 應該是 function

data() {
  return {
   question: "",
   answer: "I cannot give you an answer until you ask a question!"
  }
},

檢查此代碼框

所以你的組件Hellow World應該是這樣的:

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
   <p>
    Ask a yes/no question:
    <input v-model="question">
  </p>
  <p>{{ answer }}</p>
  </div>
</template>

<script>
import axios from "axios";
export default {
  name: 'HelloWorld',
  props: {
    msg: String,
  },
  data: () => ({
    question: "",
    answer: "I cannot give you an answer until you ask a question!"
  }),

  watch: {
    // whenever question changes, this function will run
    question: function(newQuestion, oldQuestion) {
      console.log(this.question);
      this.answer = "Waiting for you to stop typing...";
      this.getAnswer()
    }
  },

  methods: {
    getAnswer: function() {
      if (this.question.indexOf("?") === -1) {
        this.answer = "Questions usually contain a question mark";
        return;
      }
      this.answer = "Thinking...";
      let vm = this;
      axios
        .get(`https://yesno.wtf/api`)
        .then(function(response) {
          vm.answer = response.data;
        })
        .catch(function(error) {
          vm.answer = `Error connecting to the API ${error}`;
        });
    }
  },
}
</script>

然后你的main.js可以像這樣簡單:

import Vue from "vue";
import App from "./App.vue";

Vue.config.productionTip = false;

new Vue({
  el: "#app",
  render: h => h(App)
}).$mount("#app");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM