vue-router中中间件的正确方法

3qpi33ja  于 12个月前  发布在  Vue.js
关注(0)|答案(1)|浏览(118)

我在vue中创建了路由,并在每个路由之前定义了一些中间件条件。但它并不像我预期的那样工作。
router/index.js文件

const token = computed(() => useAuthStore().token);

// Main Router
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'index',
      component: LandingView,
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView,
      beforeEnter: (to, from, next) => {
        if (token.value) {
          return next({ name: 'home' });
        }
        next();
      },
    },
    {
      path: '/signup/:uid?',
      name: 'signup',
      component: SignupView,
    },
    {
      path: '/dashboard',
      name: 'dashboard',
      component: DashboardLayout,
      children: [
        {
          path: '',
          name: 'home',
          component: HomeView,
        },
        {
          path: 'profile',
          name: 'profile',
          component: ProfileView,
        },
        {
          path: 'deposit',
          name: 'deposit',
          component: DepositView,
        },
        {
          path: 'pay-amount/:amount?',
          name: 'pay-amount',
          component: PayAmountView
        },
        {
          path: 'referral',
          name: 'referral',
          component: ReferralView,
        },
        {
          path: 'salary',
          name: 'salary',
          component: SalaryView,
        },
      ],
      meta: {
        requiresAuth: true,
        requiresEmailVerify: true,
        requiresPayment: true,
        requireKyc: true,
      },
    },
    {
      path: '/email-verify',
      name: 'email-verify',
      component: EmailVerifyView,
      meta: { requiresEmailVerify: false },
      beforeEnter: (to, from, next) => {
        if (!useAuthStore().email) {
          next({ name: 'login' });
        }
        next();
      },
    },
  ],
});

router.beforeEach(async (to, from, next) => {
  const { user, getUserDetails } = useUserStore();

  if (!user?.id && !!token.value) {
    await getUserDetails();
  }
  if (to.meta.requiresAuth && !token.value) {
    return next({ name: 'login' });
  } else if (to.meta.requiresEmailVerify && !user.email_verified) {
    next({
      name: 'email-verify',
    });
  } else {
    next();
  }
});

router.afterEach(() => {
  const {sidebarVisible, setSidebarVisible} = useLayoutStore();
  if (sidebarVisible) {
    setSidebarVisible(false);
  }
});

export default router;

我的 Jmeter 盘出现了问题。如果我在/dashboard/deposit路由上,我重新加载页面,然后路由更改为/dashboard。我认为问题出在我在router.beforeEach中定义的中间件上。
我在另一条路上也遇到了同样的问题。
即使重新加载页面,我也想保持相同的路线。

1tuwyuhd

1tuwyuhd1#

我不知道你在什么模式下运行,从我的经验,当nginx配置错误时会发生这样的问题.

相关问题