本文介紹了vue-resource請求實現http登錄攔截或者路由攔截的方法,分享給大家,具體如下:
項目需求
以上是登錄超時,登錄彈窗框自動彈出來
代碼片段
路由文件
export default [ { name: 'root', path: '', component: function (resolve) { require(['你的vue文件路徑地址'], resolve); }, children: [ { name: 'applicationLayout', path: '/app/applicationLayout/:appId', component: function (resolve) { require(['你的vue文件路徑地址'], resolve); }, meta: { requireAuth: true, // 需要登錄才能進入的頁面可以增加一個meta屬性 } } ] ]
main.js 入口文件中加入以下代碼
const UNAUTHORIZED_CODE = 401;router.beforeEach((to, from, next) => { if (to.meta.requireAuth) { if (storage.get('platformUser')) { store.dispatch('loginUser', JSON.parse(storage.get('platformUser'))); //將用戶信息存儲到vuex中,供全局使用 next(); } else { store.dispatch('initLoginModal', {state: true}); //顯示登錄彈窗 next(); } } else { next(); }});//攔截http請求中返回401狀態碼,并針對其顯示登錄彈窗Vue.http.interceptors.push((request, next) => { next((response) => { if (response.body.status === UNAUTHORIZED_CODE) { //與后臺約定登錄失效的返回碼 store.dispatch('initLoginModal', {state: true}); //顯示登錄彈窗 store.dispatch('removeUser'); //移出瀏覽器中存儲的用戶信息 } return response; });});
以上便能實現登錄之前針對某些特定路由的攔截,和后臺接口授權失效時前端業務邏輯操作處理, 整篇文章僅作知識點積累,如有不妥之處,請多多包涵。希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答