vue 判断是否登录,未登录跳转到登录页

网页一进入判断是否登录,未登录跳转到登录页面

router.js


export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld,
      meta: {
        title: '首页',
        type: 'login'  // 是否需要判断是否登录,这里是需要判断
      }
    },
    {
      path: '/login',
      name: 'login',
      component: login,
      meta: {
        title: 'login',
        type: '' // 不需要鉴权
      }
    }
  ]
})

main.js


router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title
  }
  const type = to.meta.type
  // 判断该路由是否需要登录权限
  if (type === 'login') {
    if (window.localStorage.getItem('login')) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()  // 确保一定要有next()被调用
  }
})

来源:https://segmentfault.com/a/1190000016889438

原文地址:https://www.cnblogs.com/lovellll/p/10126066.html