[英]No response or error when fetching data with Vue.js using API
我剛開始學習 vue.js 需要一些幫助。 輸入問題時,我正在嘗試使用 API 從外部來源獲取答案。但我沒有得到任何響應,控制台中也沒有錯誤。 我確定錯誤可能是什么。
你快到了:) 你只需要修復代碼中的一些問題。
由於一切都發生在您的Hello World
組件中,因此無需嘗試使用道具在其中傳遞question
和answer
。 只需將所有邏輯放入組件中即可。
使用v-model
指令(雙向綁定)將question
綁定到input
,例如: <input v-model="question">
您應該在watcher
內部調用 this.getAnswer()
並且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.