vue 常用路由守卫

mac2024-03-28  31

全局前置守卫

to:router即将进入的路由对象from:当前导航即将离开的路由next:Function,进行管道中的一个钩子,如果执行完了,则导航的状态就是 confirmed (确认的);否则为false,终止导航。 router.beforeEach((to,from,next)=>{ let token = getCookie("token"); console.log(token.length); if(to.path == '/' || to.path == '/bilityform' || to.path == '/login' || token.length>0){ next(); } else{ alert('您还没有登录,请先登录'); next('/'); } })

全局后置守卫:

router.afterEach((to, from) => { console.log('全局后置守卫') })

组件内路由:

到达组件前:

//进入该路由时判断如果有token 如果没有token,转到登录页面 beforeRouteEnter:(to,from,next)=>{ var tokens=getCookie("token"); if(tokens.length>0){ next() }else{ alert("请您先登录") next('/login') } },

离开组件时:

beforeRouteLeave:(to,from,next)=>{ if(confirm("确定离开此页面吗?") == true){ next(); }else{ next(false); }

 

最新回复(0)