vuejs+axios統一接口管理

一、先創建一個api文件夾,創建一個http.js的文件
import axios from 'axios'

var instance = axios.create({
  baseURL:xxx,
  timeout:1000
});

instance.interceptors.request.use(function (config) {
  return config
},
  function (error) {
    return Promise.reject(error)
  });

instance.interceptors.response.use(function (response) {
  return response.data
},
  function (error) {
    return Promise.reject(error)
  });

//重點
export default function (method,url,data = null) {
  method = method.toLowerCase();
  if (method ===  'post'){
    return instance.post(url,data)
  } else if (method === 'get'){
    return instance.get(url,{params:data})
  } else if(method === 'delete'){
    return instance.delete(url,{params:data})
  }else if (method === 'put'){
    return instance.put(url,data)
  } else{
    console.log('未知的method'+method)
    return false
  }
}

 

二、創建一個member.js文件

引入http.js,

import req from './http.js'

export  const  LOGIN = params => req('post','/operate/login',params)

 

三、使用時,直接在.vue的文件中引用

import { LOGIN } from ‘./api/member.js’

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章