使用 pinia 在 vue 路由器中添加基于角色的路由

问题描述 投票:0回答:1

我想根据我的 pinia 商店中的用户角色加载三种可能的路线之一。我当前遇到的问题是,在设置路由器之前,pinia 存储似乎没有初始化,出现错误

Uncaught Error: [🍍]: getActivePinia was called with no active

我有办法解决这个问题吗?

仅供参考,路线设置如下

const roleOneRoutes = [
  {
    path: '/home',
    name: 'home',
    component: () => import('@/pages/RoleOne/Home'),
  },
  ...
]

const roleTwoRoutes = [
  {
    path: '/home',
    name: 'home',
    component: () => import('@/pages/RoleTwo/Home'),
  },
  ...
]

然后在索引文件中我理想地想要类似的东西

const { user } = useAuthStore()

const mappedRoutes = user.role === 'roleOne' ? roleOneRoutes : roleTwoRoutes

export const router = createRouter({
  history: createWebHistory(),
  routes: mappedRoutes
})
javascript vue.js vue-router pinia
1个回答
0
投票

Pinia store 无法在模块顶部正常访问,

useAuthStore
是一个函数而不是一个对象,因为这可以防止急切访问。应该在实际需要存储数据的地方调用它。在这种情况下,这将导致竞争条件,因为此时可能尚未设置
user

View 组件可以像这样有条件地设置:

  {
    path: '/home',
    name: 'home',
    component: () => useAuthStore().user.role === 'roleOne' 
      ? import('@/pages/RoleOne/Home')
      : import('@/pages/RoleTwo/Home'):
  },
© www.soinside.com 2019 - 2024. All rights reserved.