需求:登录验证,即未登录时跳转至登录页
路由中加入 requireAuth: true,代表进入该路由需要验证
{
path:'/Home',
name:'首页',
meta: {
requireAuth: true // 添加该字段,表示进入这个路由是需要登录的
},
component: resolve => require(['..xxxxx.vue'], resolve)
使用 router.beforeEach 在main.js中注册一个全局的函数
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requireAuth)){ // 判断该路由是否需要登录权限
if (localStorage.userId) { // 判断当前的userId
next();
}
else {
next({
path: '/loginUser',
query: {redirect: to.fullPath} // 将要跳转路由的path作为参数,传递到登录页面
})
}
}
else {
next();
}
注意:router.beforeEach方法要创建在new Vue之前。
router.beforeEach 的三个参数
to:Route:即将要进入的路由
from:Route:当前正要离开的路由
next:function()
next的用法
next() :进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。
next(false) :中断当前的导航。如果浏览器的 URL 改变了(可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。
next( { path:'/login' } ): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。
确保要调用 next 方法,否则钩子就不会被 resolved。
最后,在执行登录操作时,可以使用跳转时传递的参数回到进入登录前的路由
submitForm(){
var self = this;
//这里写登录的操作
//登录成功时
localStorage.user_id=1;
if(self.$route.query.redirect){ //如果存在参数
let redirect = self.$route.query.redirect;
self.$router.push(redirect);//则跳转至进入登录页前的路由
}else{
self.$router.push('/index');//否则跳转至首页
}
}
————————————————
版权声明:本文为CSDN博主「csdn_undefined」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_43835652/article/details/84586324