我刚开始学习 vue.js,需要一些帮助。输入问题时,我正在尝试使用 API 从外部源获取答案。但我没有得到任何响应,控制台中也没有错误。我确定错误可能是什么。
问问题
425 次
1 回答
2
你快到了:) 你只需要修复代码中的一些问题。
由于一切都发生在您的
Hello World
组件内部,因此无需尝试使用道具将question
&传递answer
到那里。只需将所有逻辑放入组件中即可。绑定
question
到input
withv-model
指令(双向绑定),如:<input v-model="question">
你应该在里面调用 this.getAnswer()
watcher
并且
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 回答