Request interceptor and response interceptor
1. Add a new http.js file, configure axios response interceptor and request interceptor. Then import the Loading component. And set the startLoading and endLoading two functions, the role is as shown by the function name.
import axios from 'axios'
import { Message, Loading } from 'element-ui'
let loading
function startLoading() {
loading = Loading.service({
lock: true,
text: '为小主拼命加载中...',
background: 'rgba(0,0,0,7)'
})
}
function endLoading() {
loading.close()
}
// 请求拦截
axios.interceptors.request.use(config => {
startLoading()
return config
}, error => {
return Promise.reject(error)
})
// 响应拦截
axios.interceptors.response.use( response => {
endLoading()
return response
}, error => {
endLoading()
Message.error(error.response.data)
return Promise.reject(error)
})
export default axios
Introduce http.js into main.js and bind it to vue
import Vue from 'vue'
import App from './App.vue'
// 引入刚才写的请求拦截
import axios from './http'
import router from './router'
import store from './store'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.config.productionTip = false
Vue.use(ElementUI);
// 绑定axios在vue属性上
Vue.prototype.$axios = axios
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')