工作內容
- 改版商家掃碼更改狀態的頁面
- 新增消息頁
- 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();
}
進展: 目前存在一些和后端數據交互上的問題,需要和后端聯調