路由设置:router/index.js
export default new Router({
routes: [
{
path: '/selfcenter',
name: 'selfcenter',
meta: {
requireAuth: true // 配置此条,进入页面前判断是否需要登陆
},
component: selfcenter
}
]
})
main.js:
/* eslint-disable no-new */
router.beforeEach((to, from, next) => {
//to 将要访问的路径
// from 代表从哪个路径跳转而来
//next 表示放行函数
// next() 直接放行 next('/xxx') 强制跳转
if (to.matched.some(res => res.meta.requireAuth)) { // 验证是否需要登陆
if (sessionStorage.getItem('sid')) { // 查询本地存储信息是否已经登陆
next();
} else {
next({
path: '/login', // 未登录则跳转至login页面
query: {redirect: to.fullPath} // 登陆成功后回到当前页面,这里传值给login页面,to.fullPath为当前点击的页面
});
}
} else {
next();
}
});
login.vue:
sessionStorage.setItem(‘sid’, res.data.data.sid); // 设置本地存储信息
this.router.push(this.router.push(this.router.push(this.route.query.redirect); // 跳转至前一页,this.$route.query.redirect是获取上面传递过来的值
————————————————
原文链接:https://blog.csdn.net/qaakd/article/details/106858661