我正在使用 Vue2 和 Vue Router 3.5 構建一個 SPA 應用程式
該應用程式有兩個身份驗證路由,“管理員”和“組織”
我有路由器設定,以便每個身份驗證保護在 url 中都有自己的前綴
'/auth/:守衛'
'/組織'
'/行政'
路由器檔案如下所示:
const routes = [
organisations,
authRoutes,
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
在組織檔案中,我回傳一個物件:
export default {
path: '/organisations',
meta: { auth: true, guard: 'organisations' },
component: () => import('../views/Organisations/OrganisationContainer.vue'),
beforeEnter: (to, from, next) => {
return store.dispatch('authentication/check')
.then(response => {
if(response) {
if(response.guard == 'admin') {
return next('/admin')
}
if(response.guard != 'organisation') {
return false
}
}else{
return next('/auth/organisation/login')
}
})
},
children: [
{
path: '/',
name: 'organisation.dash',
meta: { auth: true, route_identifier: 'dashboard', title: 'Dashboard' },
component: () => import('../views/Organisations/Dashboard/Dashboard.vue')
},
}
在以前的專案中,我使用 router.beforeEach 來處理系統中的導航。
router.beforeEach 的問題是我不想有一個大的方法來處理系統中每條路線的導航。如果我能有類似的東西會容易得多
“如果有人試圖訪問 /organisation 路由,但他們沒有登錄,則將用戶重定向到路由 /auth/organisation/login,如果他們已登錄,但他們是管理員,則將用戶重定向到他們的儀表板。”
我打算使用 beforeEnter 來實作這一點 - 但是每當我嘗試使用 next() 函式進行重定向時,都會回傳一個空白的白色螢屏。如果我回傳不帶引數的 next() 函式,它不會重定向,但頁面仍會加載。
我可能濫用了 beforeEnter 導航防護 - 但是有誰知道我如何使用 beforeEnter 導航防護重定向用戶,或者在不使用 beforeEach 并且有一個大的方法來應對的情況下實作類似的功能?
提前致謝
uj5u.com熱心網友回復:
router.beforeEach 的問題是我不想有一個大的方法來處理系統中每條路線的導航。
這種方法沒有任何問題,只要確保你在 beforeEach 中的代碼很快(不要在 beforeEach 中呼叫 API),如果你有很多代碼,沒有什么能阻止你將代碼分成多個函式,所以它是更具可讀性。
但是,如果您確實不需要使用beforeEach并且只有少數具有特定要求的路線可以使用beforeEnter,但這與beforeEach.. 首先,在您提供的代碼片段中,您beforeEach在路由上定義了一個回呼,但 beforeEach 是一個路由器級別的回呼,如 docs中所述。
您必須更改您的代碼段并替換beforeEach為beforeEnter:
export default {
path: '/organisations',
meta: { auth: true, guard: 'organisations' },
component: () => import('../views/Organisations/OrganisationContainer.vue'),
beforeEnter: (to, from, next) => {
return store.dispatch('authentication/check')
.then(response => {
if(response) {
if(response.guard == 'admin') {
return next('/admin')
}
if(response.guard != 'organisation') {
return false
}
}else{
return next('/auth/organisation/login')
}
})
},
children: [
{
path: '/',
name: 'organisation.dash',
meta: { auth: true, route_identifier: 'dashboard', title: 'Dashboard' },
component: () => import('../views/Organisations/Dashboard/Dashboard.vue')
},
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/437493.html
上一篇:在docker上運行ELK,Kibana說:無法從Elasticsearch節點檢索版本資訊
下一篇:Vue<a>標簽href屬性拼接
