vue項目使用async await 封裝 axios

es6的async await讓異步變成了同步的寫法,在vue中,能夠經過封裝axios,使得全部的請求均可以使用同步的寫法。vue

新建一個api.js文件,全局建立api實例ios

import axios from 'axios'
const qs = require('qs')
const api = {
  async get (url, data) {
    try {
      let res = await axios.get(url, {params: data})
      res = res.data
      return new Promise((resolve) => {
        if (res.code === 0) {
          resolve(res)
        } else {
          resolve(res)
        }
      })
    } catch (err) {
      alert('服務器出錯')
      console.log(err)
    }
  },
  async post (url, data) {
    try {
      let res = await axios.post(url, qs.stringify(data))
      res = res.data
      return new Promise((resolve, reject) => {
        if (res.code === 0) {
          resolve(res)
        } else {
          reject(res)
        }
      })
    } catch (err) {
      // return (e.message)
      alert('服務器出錯')
      console.log(err)
    }
  },
}
export { api }

使用能夠參考以下es6

  import { api } from 'common/js/api'
  export default {
    data () {
      return {
        list: [],
      }
    },
    created () {
      this.getList()
    },
    methods: {
      async getList () {
        let {data} = await api.get('/test/list')
        console.log(data)
        this.list = data
      }
    },
  }
相關文章
相關標籤/搜索