2

我有一个路由守卫,在使用每个路由调用它beforeEnter时可以工作,但在使用.beforeEach

在顶部的代码中,您可以看到调用/dashboard重定向时有效的示例。

但是,如果我尝试在代码底部的所有路由上全局调用它,则使用beforeEach它什么也不做。

我究竟做错了什么?

PS 我正在使用 TypeScript。

import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import store from "@/store";
import { Mutations, Actions } from "@/store/enums/StoreEnums";
import { Auth0 } from "@/auth";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    redirect: "/dashboard",
    component: () => import("@/layout/Layout.vue"),
    //beforeEnter: Auth0.routeGuard, // <--- THIS WORKS
    children: [
      {
        path: "/dashboard",
        name: "dashboard",
        component: () => import("@/views/Dashboard.vue"),
      },
      {
        path: "/add-post",
        name: "add-post",
        component: () => import("@/views/Builder.vue"),
      },
    ],
  },
  {
    // the 404 route, when none of the above matches
    path: "/404",
    name: "404",
    component: () => import("@/views/crafted/authentication/Error404.vue"),
  },
  {
    path: "/:pathMatch(.*)*",
    redirect: "/404",
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach(() => {

  store.commit(Mutations.RESET_LAYOUT_CONFIG);

  Auth0.routeGuard; // <--- THIS DOES NOT WORK

  store.dispatch(Actions.VERIFY_AUTH);

  // Scroll page to top on every route change
    setTimeout(() => {
    window.scrollTo(0, 0);
  }, 100);

});

export default router;
4

1 回答 1

0

router.beforeEach(() => { Auth0.routeGuard; })没有效果,因为该Auth0.routeGuard函数实际上并未在该语句中被调用。函数通常在任何参数(例如,Auth0.routeGuard(arg1, arg2, arg3))周围的括号中调用。

解决方案

需要使用来自以下的导航保护参数调用路由保护router.beforeEach

import { RouteLocationNormalized } from 'vue-router'
⋮
router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: Function) => {
  ⋮
  Auth0.routeGuard(to, from, next)
  ⋮
})
于 2021-10-05T23:14:53.537 回答