使用 beforeEach 時瀏覽器變得無回應
P粉724256860
P粉724256860 2024-03-19 22:53:00
0
1
311

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

在第一個 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粉724256860
P粉724256860

全部回覆(1)
P粉409742142

由於您沒有使用「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;
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!