如何使用 vue + axios 在 get 请求中使用 async/await? [英] How to use async / await in get request using vue + axios?
本文介绍了如何使用 vue + axios 在 get 请求中使用 async/await?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码,想知道如何使用 async/await 执行 try/catch 执行相同的函数:
从'vue'导入Vue从 'axios' 导入 axios新的 Vue({el: '#app',数据: {技能:[],},安装(){公理.get('http://localhost:8080/wp-json/api/v1/skills').then(响应 => {this.skills = 响应}).catch(err => (console.log(err)))}})
谢谢!
解决方案
看下面的代码:
var app = new Vue({el: '#app',异步挂载(){尝试{let response = await axios.get('http://localhost:8080/wp-json/api/v1/skills')this.skills = 响应}抓住(错误){控制台日志(错误)}}})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"><;/脚本><script src="https://unpkg.com/axios/dist/axios.min.js"></script><div id="应用程序">
I have the following code and would like to know how I can implement a try / catch with async / await executing the same function:
import Vue from 'vue'
import axios from 'axios'
new Vue({
el: '#app',
data: {
skills: [],
},
mounted() {
axios
.get('http://localhost:8080/wp-json/api/v1/skills')
.then(response => {
this.skills = response
}).catch(err => (console.log(err)))
}
})
Thank you!
解决方案
see code below:
var app = new Vue({
el: '#app',
async mounted() {
try{
let response = await axios.get('http://localhost:8080/wp-json/api/v1/skills')
this.skills = response
}catch(err){
console.log(err)
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="app">
</div>
这篇关于如何使用 vue + axios 在 get 请求中使用 async/await?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文