我有一个应用程序,用户可以以不同的角色登录,例如。seller
, buyer
and admin
。
对于每个用户,我想在同一路径上显示仪表板页面,例如。http://localhost:8080/dashboard
然而,每个用户将在不同的 vue 组件中定义不同的仪表板,例如。SellerDashboard
, BuyerDashboard
and AdminDashboard
.
所以基本上,当用户打开时http://localhost:8080/dashboard
vue 应用程序应该根据用户角色(我存储在 vuex 中)加载不同的组件。同样,我希望其他路线也能这样做。例如,当用户转到个人资料页面时http://localhost:8080/profile
应用程序应根据登录用户显示不同的配置文件组件。
因此,我希望为所有用户角色使用相同的路由,而不是为每个用户角色使用不同的路由,例如。我不希望用户角色包含在 url 中,如下所示:http://localhost:8080/admin/profile
and http://localhost:8080/seller/profile
etc...
如何使用 vue router 来实现这个场景?
我尝试使用儿童路线和每路线警卫的组合beforeEnter
根据用户角色解析路由。这是一个代码示例:
in 路由器.js:
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import store from '@/store'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'home',
component: Home,
beforeEnter: (to, from, next) => {
next({ name: store.state.userRole })
},
children: [
{
path: '',
name: 'admin',
component: () => import('@/components/Admin/AdminDashboard')
},
{
path: '',
name: 'seller',
component: () => import('@/components/Seller/SellerDashboard')
},
{
path: '',
name: 'buyer',
component: () => import('@/components/Buyer/BuyerDashboard')
}
]
},
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
in store.js:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
userRole: 'seller' // can also be 'buyer' or 'admin'
}
})
App.vue包含顶级路由的父路由器视图,例如。地图/
to Home
组件和/about
to About
成分:
<template>
<router-view/>
</template>
<script>
export default {
name: 'App',
}
</script>
And Home.vue包含嵌套router-view
对于不同用户的基于角色的组件:
<template>
<div class="home fill-height" style="background: #ddd;">
<h1>Home.vue</h1>
<!-- nested router-view where user specific component should be rendered -->
<router-view style="background: #eee" />
</div>
</template>
<script>
export default {
name: 'home'
}
</script>
但这不起作用,因为我得到了Maximum call stack size exceeded
当我调用时浏览器控制台出现异常next({ name: store.state.userRole })
in beforeEnter
。例外情况是:
vue-router.esm.js?8c4f:2079 RangeError: Maximum call stack size exceeded
at VueRouter.match (vue-router.esm.js?8c4f:2689)
at HTML5History.transitionTo (vue-router.esm.js?8c4f:2033)
at HTML5History.push (vue-router.esm.js?8c4f:2365)
at eval (vue-router.esm.js?8c4f:2135)
at beforeEnter (index.js?a18c:41)
at iterator (vue-router.esm.js?8c4f:2120)
at step (vue-router.esm.js?8c4f:1846)
at runQueue (vue-router.esm.js?8c4f:1854)
at HTML5History.confirmTransition (vue-router.esm.js?8c4f:2147)
at HTML5History.transitionTo (vue-router.esm.js?8c4f:2034)
因此什么也没有呈现。
我有办法解决这个问题吗?