new Vue({
el: '#watch-example',
data: {
question: '',
answer: 'I cannot give you an answer until you ask a question!',
},
watch: {
question() {
this.fn()
},
},
// 生命周期钩子函数 vue应用执行的时候自动帮我们调用
created() {
this.fn = _.debounce(this.getAnswer, 500)
},
methods: {
async getAnswer() {
if (this.question.indexOf('?') === -1) {
this.answer = 'Questions usually contain a question mark. ;-)'
return
}
this.answer = 'Thinking...'
// 发请求
const {
data: { answer },
} = await axios.get('https://yesno.wtf/api')
this.answer = answer
},
},
})
</script>