工作内容
- 改版商家扫码更改状态的页面
- 新增消息页
- fix 首次加载axios设置interceptors,响应无法被拦截到的bug
loadData() {
axios.get(`${API.shop_admin_status_list}/${this.orderId}?openId=${this.openId}`)
.then((res) => {
// 如果code为501会被axios拦截器拦截跳转到login
if (res.data.code === 200) {
this.dataList = res.data;
} else if (this.user_auth !== false) { // 如果状态码code不等于200且用户已登录跳转到异常页面
this.$router.replace('/message/error');
}
})
}
因为axios拦截器设置放在vue的根实例外,在vue根实例被挂载后就开始执行vue页面组件,导致首次加载的页面组件发送ajax请求无法被axios拦截器拦截。
解决方案:在根实例的生命周期created中设置axios interceptors或者放在vue的根实例声明之前
methods: {
initHttpInterceptors() {
const iswechat = this.$device.isWechat;
// Add a response interceptor
axios.interceptors.response.use((response) => {
console.log('This is an interceptors');
// Do something with response data
if (501 === response.data.code && store.getters.user_auth === false) {
Vue.nextTick(() => {
console.log(`未登录,自动跳转到登录页面...from=${app.$route.fullPath}`)
app.$store.commit(types.SAVE_LASTPATH, app.$route.fullPath)
// const oldurl=app.$route.fullPath;
//注意要用replace避免回退到未登录的订单列表又自动重新跳转到login
//router.replace('/login')
// const iswechat = this.$device.isWechat;
const wechatlogin = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc4381b971b4d6938&redirect_uri=http%3A%2F%2Fapi.huiche.sungshan.com%2Fwechat%2Foauth%2FgetOpendId.do%3Furl%3Dhttp%253A%252F%252Fh5.huiche.sungshan.com%252Flogin%253Fopenid%253DOPENID&response_type=code&scope=snsapi_base&state=123&connect_redirect=1#wechat_redirect';
if (iswechat) {
window.location = wechatlogin;
} else {
router.replace('/login');
}
});
return response;
}
console.dir(response)
return response;
}, (error) => {
// Do something with response error
console.warn('请求错误');
console.dir(error)
return Promise.reject(error);
});
}
created() {
console.log('AppRoot created!')
if (Modernizr.localstorage && window.localStorage.getItem('huiche-state')) {
console.log('about to restore state...')
//检查storage,恢复store
commit(types.RESTORE_STATE, JSON.parse(window.localStorage.getItem('huiche-state')));
}
// 配置微信jssdk
Helper.wxConfig(['getLocation'], encodeURIComponent(window.location.href));
// 触发action更新当前地理位置
this.$store.dispatch('UPDATE_LOCATION');
// 配置axios的拦截器
this.initHttpInterceptors();
},
总结
代码优化思考:可以把设置路由钩子和单例组件事件绑定的代码都封装成单独的init
方法,放在vue根实例的created中去执行这些方法,这样整个vue根实例(或者说入口js)自己内部的生命周期就变会得很清晰,可以提高代码的可读性和维护性
created() {
.....
this.initRouterEach();
this.initHttpInterceptors();
this.bindEvents();
}
进展: 目前存在一些和后端数据交互上的问题,需要和后端联调