1、在src目錄下建network檔案用于配置 axios
`。
2、在network裡面先建一個config.js檔案
export const GET="get"; //定義并導出GET請求
export const POST="post"; //定義并導出POST請求
export const path={ //定義路由對象并抛出
list:"/small4/user/detail", //定義路由(多級路由與core中axios中的路由拼接),調用誰拼接誰
}
3、在network中建一個core.js檔案
import {GET,POST} from "./config"; //導入config
import axios from "axios"; //安裝axios并引入
const instance =axios.create({ //建立一個擁有通用配置(如:路由等)axios執行個體
baseURL:"https://api.it120.cc" //通用路由與config裡的多級路由拼接
});
export function request(method,url,params){ //封裝一個函數并導出,類似于this.$axios.get(url,{})
switch(method){ //switch語句判斷是get還是poat請求
case GET: //如果是get就調用下面封裝的get請求并傳回
return get(url,params)
case POST: //post
return post(url,params)
}
};
function get(url,params){ //封裝get請求
return instance.get(url,params) //調用上面axios執行個體并return傳回
};
function post(url,params){ //封裝post請求
return instance.get(url,params)
};
4、在network中建一個index.js檔案
import {request} from "./core" //導入core
import {GET,POST,path} from './config' //導入config
const network={ //聲明一個對象
getStoreList(params){return request(GET,path.list,params)}
//自定義事件名 調用core中的request函數發送get請求,path.list是調用config裡的多級路由
}
export default network //抛出network對象 在main.js裡接收全局引入
5、在main.js裡接收全局引入
import network from './network/index' //全局引入在那都能調用
Vue.prototype.$network=network
6、之後就可以在元件中調用了
mounted() {
this.$network //調用network中的getStoreList({參數--用于傳給params})
.getStoreList({
page: 1,
pageSize: 2
})
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
});
}