vue路由的钩子函数beforeEach,afterEach导航守卫

在路由的配置文件里

const router = new VueRouter({ ... })

router.beforeEach((to, from, next) => {

// ...

})

 

-------------------------------demo01--------------------------------------

router.beforeEach((to, from, next) => {

    if (to.matched.some(res => res.meta.requireAuth)) {// 判断是否需要登录权限

        if (axiosCookie.getCookie("user_id")) {// 判断是否登录

        next()

    } else {// 没登录则跳转到登录界面

    next({

            path: '/user/login',

            query: {redirect: to.fullPath}

        })

    }

} else {

    next()

}

})

 

------------------------demo02---------------------------------------------

//路由跳转前验证登录

vueRouter.beforeEach(function(to,from,next){

// console.log(to);

// console.log(from);

// console.log(next);

// let login = localStorage.getItem('token'); //判断登录状态的; 也可以从 store 里拿到这个状态const auth = store.state.auth.IsLogin;

let login = true; //临时赋值 让函数能执行

let path = to.path

 

if (path === '/user/login') {

next()

return

}

 

if (login) {

if (path === '/') { //默认跳到首页

console.log('走了这里');

next({

path: '/Home'

})

} else {

console.log('走了默认');

next(); //进行管道中的下一个钩子

}

}else {

next({

path: '/user/login' //跳转到一个不同的地址

})

}

});

---------------------------------------------------------------------

写在main.js里axios的config配置里

const userId = axiosCookie.getCookie("user_id");

if (userId) {

//config.headers.cookie = 'user_id='+userId+';secure';

document.cookie = 'user_id='+userId+';secure';

}

 

getCookie见阿里云文件库

相关文献:

https://blog.csdn.net/latency_cheng/article/details/78580161 方法解释

https://www.cnblogs.com/wuvkcyan/p/9311155.html 方法解释

https://segmentfault.com/q/1010000015834262

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值