vue 全局钩子:路由守卫
在router index 下进行引入
Vue.use(VueRouter)
const routes = [
  {
    path: '/login',
    name: '登录',
    component: Login
  },
]
const router = new VueRouter({
  routes,
});
路由加入 路由守卫 全局钩子 访问之前检查是否登录 
// 加入导航守卫 全局钩子 访问之前,都检查下是否登录了
// beforeEach 每次访问路由之前  to:进入到哪个路由去,from:从哪个路由离开,next:路由的控制参数,常用的有next(true)和next(false)
router.beforeEach((to, from, next) => {
    // 判断该路由是否需要登录权限 去meta中找
    if (to.matched.some(auth => auth.meta.requireAuth)) {
        // 取出localStorage 中token进行判断,无则跳转至登录页
        let token = localStorage.getItem("token");
        if (token) {
            next();
        } else {
            next({
                path: "/login",
            });
        }
    } else {
        next();
    }
});
export default router;
                
            
        
浙公网安备 33010602011771号