vue使用路由拦截器来判断是否进入登录页面

vue yekong

在路由中的meta.requiresAuth添加参数来判断是否需要登录才可以访问

const routes = [
  {
    path: '/Login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "about" */ '../views/Login.vue'),
    meta: {
      title: '关于我们',
      requiresAuth: false
    }
  },
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: {
      title: '首页',
      requiresAuth: true
    }
  },
  {
    path: '/about',
    name: 'About',
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue'),
    meta: {
      title: '关于我们',
      requiresAuth: false
    }
  },
  {
    path: '/Regist',
    name: 'Regist',
    component: () => import(/* webpackChunkName: "about" */ '../views/Regist.vue'),
    meta: {
      title: '注册',
      requiresAuth: false
    }
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})
//路由拦截器
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth) {
    if (!sessionStorage.getItem("token")) {
      console.log("需要登录");
      next('/Login');
    } else {
      console.log("已登录");
      next()
    }
  } else {
    console.log("不需要登录");
    next()
  }
})

export default router

喜欢