参考Vue-Router官方文档
Vue-Router导航守卫
效果展示
1、给需要登录状态才能访问的页面路由对象的 meta 中添加配置属性
{ // 小智同学name: 'user-chat',path: '/user/chat',component: () => import('@/views/user-chat'),meta: { requiresAuth: true }
},
2、通过路由拦截器统一校验
router.beforeEach((to, from, next) => {if (to.name === 'login' || !to.meta.requiresAuth) {return next()}if (store.state.user) {return next()}Dialog.confirm({title: '该功能需要登录,确认登录吗?'}).then(() => {next({name: 'login',query: {redirect: from.fullPath}})}).catch(() => {// on cancel})
})