使用beforeEach的VUE全局路由保护不触发
我的路由防护在calling it per-route使用beforeEnter
时工作,但在使用beforeEach
将其作为global route guard调用时不起作用。
在我顶部的代码中,您可以看到调用/dashboard
重定向时起作用的示例。
但如果我尝试使用beforeEach
在代码底部的所有路由上全局调用它,则它不起任何作用。
我做错了什么?
附注:我正在使用打字稿。
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;
解决方案
router.beforeEach(() => { Auth0.routeGuard; })
无效,因为Auth0.routeGuard
函数实际上并未在该语句中被调用。调用函数时,通常使用圆括号将任何参数括起来(例如,Auth0.routeGuard(arg1, arg2, arg3)
)。
解决方案
需要使用router.beforeEach
中的navigation guard参数调用路由防护:
import { RouteLocationNormalized } from 'vue-router'
⋮
router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: Function) => {
⋮
Auth0.routeGuard(to, from, next)
⋮
})
相关文章