鍍金池/ 問答/HTML/ Vue路由攔截

Vue路由攔截

Vue.js+webpack構(gòu)建的項目,沒有使用vuex

怎么在沒有登陸的時候直接跳轉(zhuǎn)到用戶登陸界面進行登陸?

沒有登陸就禁止訪問其他界面

vue-router該怎么控制

回答
編輯回答
舊顏
  1. 在登陸的時候在本地cookie存儲一個isLogin=true,未登錄為false;
  2. 在路由頁router.js里面,寫好beforeEach((to, from, next),根據(jù)to.name來判斷接下來去那個頁面,以及isLogin是否為true;不符合要求的頁面全部跳轉(zhuǎn)到login頁面;

比如:

 if (!isLogin && to.name !==(不需要需要登陸的頁面)){
        next({
            name: 'login',
        })
    }else {
        if (is_login && toName === 'login') {
            next({
                path: '/'
            })
        } else {
            next()
        }
    }

代碼可能有點問題,但意思是這么個意思

2017年11月29日 08:03
編輯回答
尐潴豬

clipboard.png

詳情可看我的github: 項目地址

2017年7月23日 18:45
編輯回答
乖乖噠

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


next(); //前往下一個頁面

})

router.afterEach(transition => {

});

2018年1月14日 22:11
編輯回答
囍槑

傳送門:https://router.vuejs.org/zh-c...

就寫在main.js里面就可以

文檔說的很詳細,有疑問私信

2017年10月27日 21:06
編輯回答
尐飯團

參考這篇,路由攔截和http攔截都用了,不一定要用vuex,用bus或者緩存都行

https://www.cnblogs.com/guoxi...
2018年4月10日 20:57
編輯回答
尕筱澄

router.beforeEach里面判斷是否已經(jīng)登錄,沒有登錄則跳轉(zhuǎn)到登錄頁面

2017年2月6日 06:20
編輯回答
法克魷

貼代碼和注釋

const whiteList=['/login'];//不需要登錄能訪問的path
router.beforeEach((to, from, next) => {
  console.log('beforeEach');
  var userInfo= JSON.parse(sessionStorage.getItem('userInfoStorage'));//獲取緩存看是否登錄過
  if(whiteList.indexOf(to.path)<0){//訪問了需要登錄才能訪問的頁面
    if(userInfo){//登錄過來直接進去
      next();
    }else{
      if(to.path=='/login'){
        next();
      }else{
        next('/login');
      }
    }
  }
  else{
    next();
  }
});
2018年7月14日 22:44
編輯回答
寫榮
const whiteList = ['/login', '/authredirect']// 免登錄白名單

router.beforeEach((to, from, next) => {
  if (cookieGetToken()) { // determine if there has token
    /* has token*/
    if (to.path === '/login') {
      next({ path: '/' })
    }
    next()
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) { // 在免登錄白名單,直接進入
      next()
    } else {
      next('/login') // 否則全部重定向到登錄頁
    }
  }
})

文檔

2017年7月31日 15:13