axios封装api接口2

134 阅读1分钟

下载axios

npm install axios --save

util文件夹下创建ajax.js文件

    import axios from 'axios'
    export default {
      install (Vue, option = {}) {
        const http = axios.create(option)
        Vue.http = http
        Vue.prototype.$http = http
      }
    }

main.js里配置

    import Ajax from './utils/ajax'
    //设置公共接口
    Vue.use(Ajax, {
      baseURL: 'http://47.94.231.184/',
      timeout:6000
    })

4、axios我们已经设置好了,接下来编写获取数据接口的方法,我们需要在api文件夹下创建api.js文件,在该文件内进行编写,具体代码如下:

    import Vue from "vue";
    export default{
        //1获取所有的排行榜类型
        getRankType(){
            return Vue.http.get('/ranking/gender')
        },
        //2根据id获取排行榜
        getRankList(id){
            return Vue.http.get('/ranking/'+id)
        }
    }

使用

    1. 引入api.js
    import api from '@/api/api'
    2.当实例创建时获取数据
    created () {
        api.getCategory().then(response => {
          this.category = response.data
        }).catch(err => {
          console.log(err)
        })
     }