vue router验证用户是否登录

NOCO发布于 分类 WEB技术

583天前 有1个用户阅读过

router/index.js

export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld,
      meta: {
        title: 'Hello World',
        checkLogin: true  // 需要验证登录
      }
    },
    {
      path: '/login',
      name: 'login',
      component: login,
      meta: {
        title: 'login',
        checkLogin: false // 不需要验证登录
      }
    }
  ]
}) 

main.js

router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title
  }
  const checkLogin = to.meta.checkLogin
  // 判断该路由是否需要登录权限
  if (checkLogin === true) {

    if (window.localStorage.getItem('uid')) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()  // 确保一定要有next()被调用
  }
})

-- The End --

本文标题: vue router验证用户是否登录

本文地址: https://seonoco.com/blog/vue-router-check-login

本文是否有所帮助?
点赞 0
感谢支持
0
多谢反馈
评论 0
打赏

支持微信/支付宝

评论

网友