主要方法:
- to:進入到哪個路由去
- from:從哪個路由離開
- next:路由的控制參數,常用的有next(true)和next(false)
首先判斷進入的是否是login頁面?然後再判斷是否已經登陸?
已經登陸了就進入你要跳轉的頁面,沒登入就進入login頁面
為了更加明顯一點,我将頁面命名的簡單一些,ps:
-
- Login.vue是登陸頁面
-
Index.vue是全局頁面(包含公共導航元件)
A.vue是普通頁面(此處我做為首頁)
B.vue是普通頁面
//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 //此處是站内頁面,頁面在右側container裡展示
}
]
});
router.beforeEach((to, from, next) => {
const isLogin = sessionStorage.getItem('isLogin'); //擷取本地存儲的登陸資訊
if (to.name == 'login') { //判斷是否進入的login頁
if (isLogin == "true") { //判斷是否登陸
next({ name: 'a'}); //已登入,跳轉首頁(a頁面)
} else {
next(); //沒登入,繼續進入login頁
}
} else { //如果進入的非login頁
if (isLogin == "true") { //同樣判斷是否登陸
next(); //已登入,正常進入
} else {
next({ name: 'login'}); //沒登入,跳轉到login頁
}
}
});
export default router;