在应用中,通常会有以下的场景,比如商城:有些页面是不需要登录即可访问的,如首页,商品详情页等,都是用户在任何情况都能看到的;但是也有是需要登录后才能访问的,如个人中心,购物车等。此时就需要对页面访问进行控制了。
此外,像一些需要记录用户信息和登录状态的项目,也是需要做登录权限校验的,以防别有用心的人通过直接访问页面的 url 打开页面。
此时。路由守卫可以帮助我们做登录校验。具体如下:
1、配置路由的 meta 对象的 auth 属性
const routes = [
{
path: '/',
name: 'home',
component: () => import('../views/Home.vue'),
meta: { title: '首页', auth: false },
},
{
path: '/mine',
name: 'mine',
component: () => import('../views/mine.vue'),
meta: { title: '我的', auth: true },
},
]
2、在路由首页进行判断。当to.meta.auth为true(需要登录),且不存在登录信息缓存时,需要重定向去登录页面
router.beforeEach((to, from, next) => {
document.title = to.meta.title
const userInfo = sessionStorage.getItem('userInfo') || null
if (!userInfo && to.meta.auth) {
next('/login')
} else {
next()
}
})
转载自:https://juejin.im/post/5eb766296fb9a0432f0ff8c7#heading-8