Router 官网地址:
https://router.vuejs.org/zh/
https://router.vuejs.org/zh/guide/advanced/navigation-guards.html
需求介绍
Vue 项目前端工程只有用户登录时才能跳转到对应的页面,例如 home 页面, 否则跳转到 login 页面
实现思路
路由跳转之前, 进行本地记录中的用户数据判断, 如果登录成功, 得到用户ID数据, 登录失败则没有. 使用 beforeEach
实现, 关键代码
// 路由跳转之前进行判断
router.beforeEach((to, from, next) => {
// 判断跳转的页面
if (to.name === 'login') {
// 如果登录页直接跳转
next()
} else {
// 否则进行用户信息判断, 例如: 只有登录成功后才有 userId , 登录成功后设置 userId, 如: `sessionStorage.setItem('userId', '1')`
if (sessionStorage.getItem('userId') !== '') {
next()
} else {
// 如果没有 userId 数据跳转 login 页面
next({
path: '/login'
})
}
}
})
router.js 完整代码
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
Vue.use(Router)
const router = new Router({
mode: 'history',
base: '/admin',
routes: [
{
path: '/',
name: 'login',
component: () => import('./views/Login.vue')
},
{
path: '*',
name: 'notfound',
component: () => import('./views/NotFound.vue')
},
{
path: '/login',
name: 'login',
component: () => import('./views/Login.vue')
},
{
path: '/home',
name: 'home',
component: Home
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ './views/About.vue')
}
]
})
router.beforeEach((to, from, next) => {
if (to.name === 'login') {
next()
} else {
if (sessionStorage.getItem('userId') !== '')) {
next()
} else {
next({
path: '/login'
})
}
}
})
export default router
版本记录
"vue": "^2.6.10",
"vue-router": "^3.0.3",