首頁  >  問答  >  主體

使用 beforeEach 時瀏覽器變得無回應

我試圖在我的應用程式中設定一些用戶可以和不能訪問的路由,但有時我的瀏覽器會凍結並且不會給我任何錯誤訊息,所以我不知道我在做什麼錯了。

在第一個 IF 中,我檢查路由是否需要身份驗證為 true 才能訪問,如果為 false,我將使用者傳送到登入頁面。然後我檢查使用者所在的群組,如果失敗,則重定向到根頁面“/”。如果這些 IF 語句都不成立,我只會重新導向到使用者想要導覽到的頁面。

router.beforeEach((to, from, next) => {

      const isAuth = localStorage.getItem("auth");
      const userGroupRaw = localStorage.getItem("userData");
      const accessGroup = to.meta.group;
      let userGroup;
      if (userGroupRaw) {
        userGroup = JSON.parse(userGroupRaw).id_access;
      }
    
      if (to.matched.some((record) => record.meta.requiresAuth)) {
        console.log("if1");
        if (isAuth === "false") {
          next({ path: "/login" });
        }
        if (
          (accessGroup === 1 && (userGroup === 3 || userGroup === 4)) ||
          !userGroup
        ) {
          next({ path: "/" });
        }
    
        next();
      }
    
      next();
    });
    export default router;

#
P粉724256860P粉724256860213 天前307

全部回覆(1)我來回復

  • P粉409742142

    P粉4097421422024-03-20 09:41:36

    由於您沒有使用「else」語句,因此您多次呼叫 next() 並陷入無限迴圈(如評論中所述)。

    您可以使用 return 來在此時停止程式碼。

    router.beforeEach((to, from, next) => {
    
      const isAuth = localStorage.getItem("auth");
      const userGroupRaw = localStorage.getItem("userData");
      const accessGroup = to.meta.group;
      let userGroup;
      if (userGroupRaw) {
        userGroup = JSON.parse(userGroupRaw).id_access;
      }
    
      if (to.matched.some((record) => record.meta.requiresAuth)) {
        if (isAuth === "false") {
            return next({
                path: "/login"
            });
        }
        if (
            (accessGroup === 1 && (userGroup === 3 || userGroup === 4)) ||
            !userGroup
        ) {
            return next({
                path: "/"
            });
        }
        // next(); - this is not needed as the preceding next always gets called.
      }
      next();
    })
    
    export default router;

    回覆
    0
  • 取消回覆