Vue-router路由判斷頁面未登錄跳轉到登錄頁面


router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requireAuth)){  // 判斷該路由是否需要登錄權限
    if (token) {  // 判斷當前的token是否存在
      next();
    }
    else {
      next({
        path: '/login',
        query: {redirect: to.fullPath}  // 將跳轉的路由path作為參數,登錄成功后跳轉到該路由
      })
    }
  }
  else {
    next();
  }
});

  

在這之前是給路由加一個meta屬性:

{
    path: '/index',
    meta: {
      title: '',
      requireAuth: true,  // 添加該字段,表示進入這個路由是需要登錄的
    },
}

 

注意:但是事實是登錄的時候大多數時候並不進行跳轉,所以這里需要在login跳轉的路徑中再加一段:

if(this.$route.query.redirect){
//     let redirect = decodeURIComponent(this.$route.query.redirect);
       let redirect = this.$route.query.redirect;
       this.$router.push(redirect);
}else{
       this.$router.push('/');
 }

 


免責聲明!

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



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