使用beforeEach的VUE全局路由保护不触发 [英] Vue Global Route Guard using beforeEach does not trigger

查看:41
本文介绍了使用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)
  ⋮
})

这篇关于使用beforeEach的VUE全局路由保护不触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆