vue登录之 Vue-router判断页面未登录跳转到登录页面

在main.js中判断是否需要登录
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
      //这里判断用户是否登录,验证本地存储是否有token
      if (!localStorage.token) { // 判断当前的token是否存在
          next({
              path: '/login',
              query: { redirect: to.fullPath }
          })
      } else {
          next()
      }
  } else {
      next() // 确保一定要调用 next()
  }
})
之后在路由配置文件中给需要登录的路由加一个meta
meta: { requiresAuth: true }
这样就好啦,如果哪里有不足可以和我交流

猜你喜欢

转载自www.cnblogs.com/ymdzha/p/9219382.html