vue路由守卫
一、全局路由守卫
//全局守卫写在main中
//router对象调用
//.beforeEach((进入到哪一个路由,从哪一个路由离开,对应的函数)=>{})
router.beforeEach((to, from, next) => {
const toPath = to.path;
// 将要进入的路径非'/login'
if (toPath !== '/login') {
// 用户未登录
if (!window.sessionStorage.getItem('Authorization')) {
router.push('/login');
}
// 其他
else {
next();
}
}
// 将要进入的路径'/login'
else {
next();
}
});
next() 进入该路由。
next(false): 取消进入路由,url地址重置为from路由地址(也就是将要离开的路由地址)。
next 跳转新路由,当前的导航被中断,重新开始一个新的导航。
我们可以这样跳转:next(‘path地址’)或者next({path:’’})或者next({name:’’})
且允许设置诸如 replace: true、name: ‘home’ 之类的选项
以及你用在router-link或router.push的对象选项
二、路由独享守卫
//路由独享守卫,写在router路由中
{path:"/admin",name:"admin",component:admin,
//beforeEnter(to,form.next)=>{判断是否登陆代码},点击进入admin也面时,路由独享守卫启用
beforeEnter:(to,form,next)=>{
//alert('非登陆状态,不能访问此页面!');
//next('/login');
//判断是否登录 store.gettes.isLogin === false
if(to.path == '/login' || to.path == '/register' ){
next();
}else{
alert("还没有登录,请先登录!");
next('/login');
}
}
},
三、组件内路由守卫
/*组件内守卫,写在组件中
组件内守卫使用beforeRouteEnter:(to,form,next)=>{代码}方法,
注意:该方法是在页面加载前执行。拿不到this.name的值,
利用好next的回调参数,拿到对应的内容,这个时候请使用vm.name,异步加载*/
beforeRouteEnter:(to,form,next)=>{
// alert("hello" + this.name);
// next();
//to和form,可以判断要进入的路由名称,从哪个路由离开
next(vm => {
alert("Hello"+vm.name);
})
}
//beforeRouteLeave:(to,form,next)=>{代码}方法,在用户离开页面前加载。
beforeRouteLeave:(to,form,next)=>{
if(confirm("确定离开吗?") == true ){ //询问是否离开==true
next(); //确认离开
}else{
next(false); //false不离开
}
}
原文链接:https://blog.csdn.net/weixin_43848576/article/details/93722997
原文链接:https://segmentfault.com/a/1190000015727279