export const myAjax=function createHttpClient(ajaxConfig) {
let httpClient = null;
if (ajaxConfig) {
httpClient = axios.create(ajaxConfig);
httpClient.interceptors.request.use(...);
httpClient.interceptors.response.use(...);
else {
httpClient = axios.create()
}
return httpClient;
}html
axios:Axios 是一個基於 promise 的 HTTP 庫,能夠用在瀏覽器和 node.js 中。node
詳細可參考官方文檔:https://www.kancloud.cn/yunye/axios/234845ios
export const ajaxMixin = { created() { const ajaxConfig = this.$options.myAjaxConfig this.$_myAjax = myAjax(ajaxConfig) }, }
$options:當前 Vue 實例的初始化選項(在選項中包含自定義屬性(myAjaxConfig)
3.在new Vue實例化前混入ajaxMixin
Vue.mixin(ajaxMixin) new Vue({ router, store, i18n, render: h => h(App), }).$mount('#app')
Vue.mixin( mixin ):全局註冊一個混入,影響註冊以後全部建立的每一個 Vue 實例,向組件注入自定義的行爲。
4.在具體模塊中自定義myAjaxConfig,以及調用this.$_myAjax請求後臺數據
export default { ... myAjaxConfig: { showSpinner: true, baseURL: '/api/F64/', }, methods: { // 從服務器加載畫面所需數據 loadAllData(eigyousyoIdValue) { return this.$_myAjax .post( 'GetGoodsInfo', {}, { headers: { eigyousyoId: eigyousyoIdValue, }, } ) },
...
}
詳細使用方式見:http://www.javashuo.com/article/p-ecrdmfba-hh.htmlajax