如何在使用vue + axios的get请求中使用async / await?

时间:2018-05-20 17:10:28

标签: async-await vuejs2 axios

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

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

谢谢!

1 个答案:

答案 0 :(得分:9)

请参阅以下代码:



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>
&#13;
&#13;
&#13;