1.新建一个js文件,假设为ajax: 代码如下->
// 引入本地axis包
import axiosfrom "axios/index";
引入ele门插件 按需引入
import {Loading, Message, Notification}from 'element-ui'
引入你定义的路由
import routerfrom '../router/index'
引入你定义的vuex
import storefrom '../store/index'
进行axios默认配置
axios.defaults.timeout =5000
axios.defaults.headers.post['Content-Type'] ='application/json;';
var that =this
// http请求拦截器
var loadinginstace
axios.interceptors.request.use(config => {
// element ui Loading方法
loadinginstace = Loading.service({fullscreen:true})
const token = window.localStorage.getItem('setTokenTicket')
if (token) {
config.headers['token'] = token
}
return config
}, error => {
loadinginstace.close()
Message.error({
message:'加载超时'
})
return Promise.reject(error)
})
// http响应拦截器
var that =this
axios.interceptors.response.use(data => {// 响应成功关闭loading
loadinginstace.close()
if (data.data.code ===401) {
store.commit('userOut')
localStorage.clear()
setTimeout(function () {
Notification.success({
title:'没有权限',
message:'token失效,跳转到登录页面'
})
router.replace({
path:'/user'
})
},1500)
return false
}else if (data.data.code ===500) {
Notification.success({
title:'数据错误',
message: data.data.msg
})
return false
}else if (data.data.code ===2000) {
Notification.success({
title:'参数错误',
message: data.data.msg
})
return false
}else if (data.data.code ===0) {
return data
}
}, error => {
console.log(error)
loadinginstace.close()
Message.error({
message:'加载失败'
})
Notification.success({
title:'网络错误',
message:'请检查网络连接或者联系管理员'
})
return Promise.reject(error)
})
export default axios
2. 挂载原型上面 vue
// ajax第一步定义的文件
import axiosfrom './config/ajax';
Vue.prototype.$axios = axios;
3.使用
this.$axios.method() // 具体看文档
网友评论