I encapsulated Axios in the Vue project, hoping to uniformly handle the information returned by the interface and pop up a custom pop-up plug-in.
encapsulated axios is mounted to vue via Vue.prototype.$cAxios = cAxios;
component to be used directly in App.vue after testing, but it cannot be triggered directly in the encapsulated js to display the undefined.
I can trigger normally when I introduce elementUI into js. I printed it and found that elementUI introduced more directive and service than I did.
beginners of Vue, ask the bosses for advice on how to properly package this plug-in.
< hr >
/ / main.js
/ / The Vue build version to load with the import
command
/ / (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from "vue"
import App from". / App"
/ / Route injection
import router from". / router/route.js"
import md5 from "js-md5"; / / md5 encryption
Vue.prototype.$md5 = md5;
import cAxios from". / fun/cAxios" / / Secondary package axios
Vue.prototype.$cAxios = cAxios;
import ElementUI from "element-ui";
import" element-ui/lib/theme-chalk/index.css";
Vue.use (ElementUI);
import localAlert from". / components/localAlertIndex.js";
Vue.use (localAlert);
Vue.config.productionTip = false
/ eslint-disable no-new /
new Vue ({
el:"- sharpapp",
router,
components: {App},
template:"< App/ >"
})
/ / the following is packaged axios
import axios from "axios"
import localAlert from" @ / components/localAlertIndex.js";
import {Loading} from "element-ui";
/ add request interceptor
axios.interceptors.request.use (function (config) {
/ / do something before sending the request
return config;
}, function (error) {
/ / do something wrong to the request
return Promise.reject (error);
});
/ / add response interceptor
axios.interceptors.response.use (function (response) {
/ / do something to the response data
if (response.data.returnCode = "999999") {
console.log("Loading",Loading);
console.log("LoadingS",Loading.service);
console.log("localAlert",localAlert);
// localAlert.$loading();
}
console.log (response);
return response;
}, function (error) {
/ / do something to the response error
return Promise.reject (error);
});
export default axios;
< hr > / / define the js of the plug-in
import localAlert from". / localAlert.vue"
let $vm;
export default {
install (Vue, options) {
if (!$vm) {
const LocalAlert = Vue.extend(localAlert);
$vm = new LocalAlert({
el: document.createElement("div")
});
document.body.appendChild($vm.$el);
}
$vm.ifShow = false;
let loading = {
on(text) {
$vm.ifShow = true;
$vm.message = text;
}
};
if (!Vue.$loading) {
Vue.$loading = loading;
}
// Vue.prototype.$loading = Vue.$loading;
Vue.mixin({
created() {
this.$loading = Vue.$loading;
}
})
}
}