How to use async / await in get request using vue + axios?

允我心安 提交于 2019-12-04 23:56:25

问题


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!


回答1:


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>


来源:https://stackoverflow.com/questions/50437420/how-to-use-async-await-in-get-request-using-vue-axios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!