Vue router拦截 如果用户并未登录直接跳转到登录界面(最简单的cookie演示)

router.beforeEach(function(to,from,next){
console.log('路由拦截')
console.log(to.name)
console.log(from.name)
if(to.name=='login'){
next();
}else{
if($.cookie('userIsLogin')=='true'){
next();
}else{
next({path:'/login'});
}
}
})

 我的登录地址是login,如果userIsLogin并没有写true的话,将在点击每一个连接的时候直接跳转到登录界面,

但是如果用户直接通过连接进入,那将直接可以查看此链接的内容,并不会进行拦截。

这个时候需要在最大的组件中添加如下代码

var app = new Vue({
el: '#app',
router,
components: {Container},
mounted: function(){
if(!($.cookie('userIsLogin')=='true')){
//如果用户并未登录 直接跳转到登录界面
this.$router.push('/login')
}
}
})

或者

将路由校验放置于Vue实例之前 也是可以的

上一篇:iOS面试必备-iOS基础知识


下一篇:linux命令行解析函数介绍