在Vue中使用vue-router、route guard & Vuex动态根目录结构。

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

我有一个vue-router,是这样的。

const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/',
      children: [
        {
        {
          path: 'main',
          name: 'main',
          component: () => import(/* webpackChunkName: "main" */ './views/main/Main.vue'),
          children: [
            {
              path: 'dashboard',
              name: 'main-dashboard',
              component: () => import(/* webpackChunkName: "main-dashboard" */ './views/main/Dashboard.vue'),
            },
...

有一些路由守卫,一旦用户登录,他们就会被引导到... ... /BASE_URL/main/dashboard.

  public beforeRouteEnter(to, from, next) {
    routeGuardMain(to, from, next);
  }

  public beforeRouteUpdate(to, from, next) {
    routeGuardMain(to, from, next);
  }

const routeGuardMain = async (to, from, next) => {
  if (to.name === 'main') {
    next({ name: 'main-dashboard'});
  } else {
    next();
  }
};

我在储存 user_idaccount_id 在Vuex状态下,我希望能够创建一个像这样的url结构。

BASE_URL/<account_id>/dashboard

但我无法访问 account_id 从存储中获取(我已经设置了getters来获取相关参数),并在路由保护的重定向过程中把它作为参数传递(它的null未定义,所以我想我需要在某个地方等待?

我可以为没有路由保护的路径设置动态的URL,但不知道如何在有了路由保护的情况下做到这一点。

我看了vue-router的文档,但无法解决。

请谁能建议我如何实现目标url结构?抱歉我的前端技术不足,而且我是Vue.js的新手。

vue.js vuex vue-router
1个回答
0
投票

找到一个类似于这个链接的解决方案。

定义Vue-Router路由时访问Vuex状态

const startRouteGuard = async (to, from, next) => {
  await dispatchCheckLoggedIn(store);
  if (readIsLoggedIn(store)) {
      if (to.path === '/login' || to.path === '/') {
        if (store.getters.userMembership.account_id === null) {
          const watcher = store.watch(store.getters.userMembership.account_id, account_id => {
            watcher(); // stop watching
            next({ name: 'main', params: { account_id: account_id}});
          });
        } else {
          const account_id = store.getters.userMembership.account_id;
          next({ name: 'main', params: { account_id: account_id}});
        }
      } else {
        next();
      }
  } else if (readIsLoggedIn(store) === false) {
    if (to.path === '/' || (to.name as string).startsWith('main')) {
      next({name: 'login'});
    } else {
      next();
    }
  }
};
© www.soinside.com 2019 - 2024. All rights reserved.