使用 API 使用 Vue.js 获取数据时无响应或错误

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

我刚开始学习 vue.js,需要一些帮助。当输入问题时,我试图使用 API 从外部来源获取答案。但我没有得到任何响应,控制台中也没有错误。我确定错误可能是什么。

这是我的代码 link https://codesandbox.io/embed/vue-template-dk71y

你就快完成了:)你只需要修复代码中的一些问题。

  1. 由于一切都发生在您的 Hello World 组件中,因此无需尝试使用道具将 questionanswer 传递到其中。只需将所有逻辑放在组件中即可。

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

  3. 您应该在 watcher

  4. 中调用 this.getAnswer()
  5. datashould be a function

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

Check this codesandbox

所以你的组件 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");