0

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

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

4

1 回答 1

2

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

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

  2. 绑定questioninputwithv-model指令(双向绑定),如:<input v-model="question">

  3. 你应该在里面调用 this.getAnswer()watcher

  4. 并且data 应该是一个函数

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");
于 2019-10-10T10:50:23.330 回答