vue3 异步加载中使用 watch
异步数据的加载 Vue 通过 watch 选项提供了一个更通用的方法,来响应数据的变化。
以下实例我们使用 axios 库,后面会具体介绍。
<script src="https://cdn.staticfile.org/vue/3.2.36/vue.global.min.js"></script>
<script src="~/js/Compententysub.js"></script>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<style>
.class1 {
background: #444;
color: #eee;
}
</style>
<div id="watch-example">
<p>
输入一个问题,以 ? 号结尾输出答案:
<input v-model="question" />
</p>
<p>{{ answer }}</p>
</div>
<script>
const watchExampleVM = Vue.createApp({
data() {
return {
question: '',
answer: '每个问题结尾需要输入 ? 号。'
}
},
watch: {
// 每当问题改变时,此功能将运行,以 ? 号结尾,兼容中英文 ?
question(newQuestion, oldQuestion) {
if (newQuestion.indexOf('?') > -1 || newQuestion.indexOf('?') > -1) {
this.getAnswer()
}
}
},
methods: {
getAnswer() {
this.answer = '加载中...'
axios
.get('/try/ajax/json_vuetest.php')
.then(response => {
this.answer = response.data.answer
})
.catch(error => {
this.answer = '错误! 无法访问 API。 ' + error
})
}
}
}).mount('#watch-example')
</script>