Vue全局判断是否登陆

在Vue中Router是一个非常重要的对象,那么在判断是否登陆的时候,需要一个一个页面去写吗?并不是的。可以通过router来实现,这个和aop有点相似

router=>index.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.sessionStorage.getItem('UserInfo')) {
      console.log(window.sessionStorage.getItem('UserInfo'));
      next()
    } else {
      next('/login')
    }
  } else {
    next()  // 确保一定要有next()被调用
  }
})

 路由中加上meta标签,type是指向的回调模块。

{
      path: '/index',
      name: 'index',
      component: ()=>import("@/components/index"),
      meta:{
        title:'首页',
        type:'login'
      }
    }

  这个对象还是非常好玩的。

猜你喜欢

转载自www.cnblogs.com/ZaraNet/p/11076401.html