路由守卫

如果有些页面需要登录才能进入 这时候就需要路由守卫了

在router/index.js里面想要拦截的地方加这一段代码就行了

路由独享的守卫
在这里插入图片描述

vue-router路由守卫基本使用
作用
通过路由拦截,来判断用户是否登录,该页面用户是否有权限浏览
全局路由守卫
全局前置守卫:路由跳转前调用

router.beforeEach((to,from,next)=>{
console.log(to); // 即将要跳转的路由
console.log(from); // 即将要离开的路由
next() // 一定要调用 执行下一个钩子 全部钩子执行完 跳转到地址栏上的路由
})

router.beforeEach((to,from,next)=>{
console.log(to);
console.log(from);
next(false) // 中断当前路由跳转
})

router.beforeEach((to,from,next)=>{
console.log(to);
console.log(from);
next('/test') // 跳转到指定路由 此处代码写法错误
})

跳转到指定路由,此处代码写法错误,会造成死循环直到浏览器栈溢出,调用next()的同时也会执行多一次beforeEach

正确写法是先判断要离开的路由是什么再跳转

router.beforeEach((to, from, next) => {
console.log(to);
console.log(from);
if (to.path == "/home") {
next('test');
next({ path: '/test' }) //或者这样写
}
});

全局后置守卫:路由跳转之后再执行

router.afterEach((to,from)=>{
console.log(to);
console.log(from);
})

路由独享的守卫
在路由配置上直接定义 beforeEnter 守卫

const routes = [
{
path: "/home",
component: () => import(/* webpackChunkName: "user" */ "../views/Home"),
beforeEnter:(to,from,next)=>{
console.log(to);
console.log(from);
next()
}
},
];

效果和beforeEach差不多

原文地址:https://www.cnblogs.com/hellofangfang/p/15384572.html