前言
vue中用路由守衛(wèi)來做是否登陸判斷,此處我以后臺管理項目為例旗扑,如下圖:
admin.jpg
主要方法:
router.beforeEach((to,from,next)=>{ })
- to:進入到哪個路由去
- from:從哪個路由離開
- next:路由的控制參數(shù)维哈,常用的有next(true)和next(false)
首先判斷進入的是否是login頁面例隆?然后再判斷是否已經(jīng)登陸阔逼?
已經(jīng)登陸了就進入你要跳轉(zhuǎn)的頁面,沒登錄就進入login頁面
為了更加明顯一點烛谊,我將頁面命名的簡單一些风响,ps:
- Login.vue是登陸頁面
- Index.vue是全局頁面(包含公共導(dǎo)航組件)
A.vue是普通頁面(此處我做為首頁)
B.vue是普通頁面 - 404.vue是走丟了的404頁面
實現(xiàn)代碼
//router.js
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router);
const children = [
{
path: 'a',
name: 'a',
component: () => import('./views/A.vue'),
meta: {
title: 'a頁面',
keepAlive: false // 無緩存
}
},
{
path: 'b',
name: 'b',
component: () => import('./views/B.vue'),
meta: {
title: 'b頁面',
keepAlive: true // 有緩存
}
},
{
path: '404',
name: '404',
component: () => import('./components/404.vue')
}
];
const router = new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{ path: '/', redirect: '/a' },
{ path: '*', redirect: '/404' },
{
path: '/login',
name: 'login',
component: () => import('./components/Login.vue')
},
{
path: '/',
component: () => import('./components/Index.vue'), //index是上圖左邊的公共菜單
children //此處是站內(nèi)頁面,頁面在右側(cè)container里展示
}
]
});
router.beforeEach((to, from, next) => {
const isLogin = sessionStorage.getItem('isLogin'); //獲取本地存儲的登陸信息
if (to.name == 'login') { //判斷是否進入的login頁
if (isLogin == "true") { //判斷是否登陸
next({ name: 'a'}); //已登錄丹禀,跳轉(zhuǎn)首頁(a頁面)
} else {
next(); //沒登錄状勤,繼續(xù)進入login頁
}
} else { //如果進入的非login頁
if (isLogin == "true") { //同樣判斷是否登陸
next(); //已登錄,正常進入
} else {
next({ name: 'login'}); //沒登錄双泪,跳轉(zhuǎn)到login頁
}
}
});
export default router;