猿问

Axios配置文件中this为undefined?

问题描述
在this.$router发现没这个属性,后面查了下this为undefined
相关代码
//请把代码文本粘贴到下方(请勿用图片代替代码)importaxiosfrom'axios'import{Loading,Message}from'element-ui'importDebouncefrom'lodash/debounce'
constAxios=axios.create({
baseURL:'/',
timeout:'10000',
responseType:'json',
withCredentials:true,
headers:{
"Content-Type":"application/json;charset=UTF-8"
}
});letneedLoadingRequestCount=0;letloadingObj;
Axios.interceptors.request.use(
config=>{
console.log(this);
if(config.showLoading){
showFullScreenLoading();
}
returnconfig;
},
error=>{
if(needLoadingRequestCount!==0){
loadingObj.close();
}
Message({
showClose:true,
message:'服务器有误!请稍后重试',
type:"error"
});
returnPromise.reject(error);
}
);
Axios.interceptors.response.use(
res=>{
//console.log(this);
if(res.config.showLoading){
tryHideFullScreenLoading();
}
if(res.data.code!==200&&res.data.message){
Message({
showClose:false,
type:"error",
center:true,
message:res.data.message?res.data.message:"服务器繁忙!请重试"
});
if(res.data.code===9999100){
this.$router.push('/login');
}
returnPromise.reject(res.data.message);
}
returnres;
},
error=>{
if(needLoadingRequestCount!==0){
loadingObj.close();
}
Message({
showClose:true,
message:'服务器繁忙!请稍后重试',
type:"error"
});
returnPromise.reject(error);
}
);
functionshowFullScreenLoading(){
if(needLoadingRequestCount===0){
loadingObj=Loading.service({
lock:true,
text:"Loading",
spinner:'el-icon-loading',
background:'rgba(0,0,0,0.7)'
});
}
needLoadingRequestCount++
}functiontryHideFullScreenLoading(){
if(needLoadingRequestCount<=0)return
needLoadingRequestCount--
if(needLoadingRequestCount===0){
Debounce(tryCloseLoading,300)();
}
}functiontryCloseLoading(){
if(needLoadingRequestCount===0){
loadingObj.close();
}
}exportdefault{
header(token){
Axios.defaults.headers.common['Authorization']=`ticket${token}`;
},
post:(url,data,config={showLoading:true})=>Axios.post(url,data,config),
get:(url,config={showLoading:true})=>Axios.get(url,config),
delete:(url,config={showLoading:true})=>Axios.delete(url,config)
}
你期待的结果是什么?实际看到的错误信息又是什么?
明明都是箭头函数啊,this怎么会丢呢
宝慕林4294392
浏览 1478回答 2
2回答

明月笑刀无情

楼主,你好!当前的this已经换过了,不再是vue实例化的对象了。所以可以再main.js里初始化实例对象的时候挂载到window下面。//main.js...window.vm=newVue({});...//axioswindow.vm.$router.push('..')
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答