vue router验证用户是否登录

发布于 分类 WEB技术

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

本页面显示内容已针对移动端进行优化,点击查看完整版本