如何使用vue + axios在获取请求中使用异步/等待? [英] How to use async / await in get request using vue + axios?

查看:103
本文介绍了如何使用vue + axios在获取请求中使用异步/等待?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,想知道如何使用async/await执行相同的功能来实现try/catch:

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)))
  }
})

谢谢!

推荐答案

请参见以下代码:

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在获取请求中使用异步/等待?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆