vue不断填坑中,首先要在需要拦截的路由添加meta: {requireAuth: true},然后使用路由钩子函数beforeEach拦截处理。

import Router from 'vue-router'
const routes = [
    {
        path: '/controlPanel',
        name: 'ControlPanel',
        component: ControlPanel,
        meta: {
          requireAuth: true,
        },
    }
]
const VueRouter = new Router ({
  routes,

});
VueRouter.beforeEach((to, from, next) => {
  if (to.matched.some((r) => r.meta.requireAuth)) {
    let user = JSON.parse(localStorage.getItem('user'));
    if (user) {   //判断是否已经登录
      console.log('这是通过拦截后到处理',from);

      next();
    } else {
      next({
        path: '/login',
        query: {redirect: to.fullPath}   //登录成功后重定向到当前页面
      });
    }
  } else {
    console.log('这是拦截');
    next();
  }
  //如果本地 存在 token 则 不允许直接跳转到 登录页面
  if(to.fullPath === "/login"){
    if(localStorage.getItem('user')){
      next({
        path:from.fullPath
      });
    }else {
      next();
    }
  }
});
export default VueRouter;

 

Logo

前往低代码交流专区

更多推荐