<template>
<div id="app">
<p>
输入问题(以问号结尾):
<input v-model="question">
</p>
<p>{{ answer }}</p>
</div>
</template>
<script>
import _ from 'lodash';
import axios from 'axios';
export default {
data(){
return{
question: '',
answer: '请输入问题~~'
}
},
watch: {
// 如果 `question` 发生改变,这个函数就会运行
question(value) {
this.answer = '正在输入...';
this.debouncedGetAnswer()
}
},
mounted() {
// `_.debounce` 是一个通过 Lodash 限制操作频率的函数。
this.debouncedGetAnswer = _.debounce(this.getAnswer, 500)
},
methods: {
getAnswer() {
if (this.question.indexOf('?') === -1) {
this.answer = '请以问号结尾~~'
return
}
this.answer = '处理中...'
var vm = this
axios.get('https://yesno.wtf/api')
.then(function (response) {
// 首字母大写
vm.answer = _.capitalize(response.data.answer)
})
.catch(function (error) {
vm.answer = 'Error! Could not reach the API. '
})
}
}
}
</script>
返回结果7种状态:
请输入问题~~
正在输入…
请以问号结尾~~
处理中…
yes
no
Error! Could not reach the API.