vue中全局前置守衛router.beforeEach出現死循環日記


今天我用vue寫登錄的時候,想利用全局前置守衛來進行路由控制,判斷是否登錄和是否有此資源寫完后會發現頁面空白,並進入死循環。

設置路由

 1 const routes = [
 2   {
 3     path: '/',
 4     redirect: "/login" // 重定向
 5   },
 6   {
 7     path: '/home',
 8     component: Home,
 9     children: [ // 子路由
10       {
11         path: '',
12         name: 'home',
13         component: Dash,
14         meta: {
15           auth: true
16         }
17       },
18       {
19         path: 'about',
20         name: 'About',
21         component: () => import('../views/About.vue'),
22         meta: {
23           auth: true
24         }
25       },
26       {
27         path: 'list',
28         name: 'list',
29         component: () => import('../views/List.vue'),
30         meta: {
31           auth: true
32         }
33       },
34       {
35         // path: 'detail',
36         path: 'detail/:id', // id代表動態路由,值是不固定的
37         name: 'detail',
38         component: () => import('../views/Detail.vue'),
39         meta: {
40           auth: true
41         }
42       }
43     ] 
44   },
45   {
46     path: '/login',
47     name: 'login',
48     component: () => import('../views/Login.vue'),
49     meta: {
50       auth: true
51     }
52   }, 
53   {
54     path: "*", // 匹配所有路由
55     name: "404",
56     component: () => import('../views/NotFound.vue')
57   }
58 ]

錯誤代碼

// 注冊全局前置守衛
// 在訪問路由之前進行攔截
router.beforeEach((to, from, next) => {
  // 獲取 token, 登錄的標識
  var token = sessionStorage.getItem("token");
  if(to.meta.auth) { // 判斷是否有這個路徑
    if(token) { // 再次判斷是否已經登錄過
      next()
    } else {
      next({ // 沒有登錄過,導向登錄頁
        path: '/login',
        query: {redirect: to.fullPath} // 記錄原本想訪問的路徑
      })
    }
  } else {
    next(); 
  }

正確代碼

 1 // 注冊全局前置守衛
 2 // 在訪問路由之前進行攔截
 3 router.beforeEach((to, from, next) => {
 4   // 獲取 token, 登錄的標識
 5   var token = sessionStorage.getItem("token");
 6   
 7   if(token) { // 判斷是否已經登錄過
 8     next()
 9   } else { 
10     if(to.meta.auth && to.path ==='/login') { // 如果有此資源且是登錄頁
11       next();
12     } else if(!to.meta.auth){ // 沒有此資源,到404頁面
13       next()
14     } else { // 有此資源,沒有登陸過,也不是登錄頁
15       next({path: '/login'})
16     }
17   }
18 
19 })

原因:next({path: '/login'}) 會再次調用 router.beforeEach((to, from, next) ,在錯誤實例中沒有出口,導致死循環


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM