????在vue開發(fā)過程中,有時(shí)候一個(gè)頁面使用到很多接口,如果每個(gè)接口都是用import {xx,xx,xx} from 'xxxxx'這樣的方式引入調(diào)用,顯得有些麻煩。能使用this.xxx.xxx這樣的方式調(diào)用顯得簡單一些。this.xx.xx這樣的方式調(diào)用的原理是把接口暴露在vue的原型上,現(xiàn)在就可以通過this的方式調(diào)用,this.xx是為了統(tǒng)一一下,api都用同一個(gè)vue的一個(gè)屬性包裝調(diào)用。
全局的接口文件global.js
// 封裝好的axios.js
import?{?axiosPost?}?from?'../utils/axios'
// 接口地址
import?{?Global?}?from?'../config/config.url'
/**
?*?上傳文件
?*?@param?{String}?file?文件對象
?*/
export?function?fileUpload?(file)?{
??let?formData?=?new?FormData()
??//?上傳文件參數(shù)
??formData.append('file',?file)
??return?axiosPost(Global.fileUpload,?formData,?true,?false,?{
????headers:?{
??????'Content-Type':?'application/x-www-form-urlencoded'
????}
??})
}
把創(chuàng)建好的每個(gè)模塊的接口文件引入接口全局文件
一、js版本
// 接口全局文件/api/index.js
全局注冊組件
import?*?as?global?from?'./global'
const?API?=?{
??global,
}
export?default?{
??install?(Vue)?{
????Vue.prototype.$api?=?API
??},
??...API
}
一、ts版本
// 接口全局文件/api/index.js
全局注冊組件
import?{?ApiType?}?from?'./index.d'
import?*?as?global?from?'./global'
const?API?=?{
??global
}
declare?module?'vue/types/vue'?{
??interface?Vue?{
????$api:?ApiType;
??}
}
const?ApiPlugin:?PluginObject<Vue>?=?{
??install?(Vue)?{
????Vue.prototype.$api?=?API
??},
??...API
}
export?default?ApiPlugin
在/api/index.d.ts文件中定義ts的接口
import?{?AxiosPromise?}?from?'axios'
interface?Global?{
??fileUpload:?(file:?File)?=>?AxiosPromise;
??xxx:?(data:?any)?=>?any;
?xx:?(data:?any)?=>?any;
}
// 接口對應(yīng)的字段映射,方便調(diào)用的時(shí)候,有提示選擇
export?interface?ApiType?{
??global:?Global;
}
在main.js中直接用引用并Vue.use進(jìn)行注冊,裝載
import?Vue?from?'vue'
import?API?from?'./api'
Vue.use(API)