首页 > 技术文章 > 路由守卫

myqinyh 2021-09-27 21:04 原文

与path平级处写

path:'mine',
        component:Mine,
        //需要登录
        meta:{
          needLogin:true
        }
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

//路由守卫
router.beforeEach((to, from, next) => {
  // ...
  // console.log(this.$store.state.isLogin)
  console.log(to)
  // console.log(from)
  console.log(next)
  //如果需要登录
  if(to.meta.needLogin){
    //确认登录状态
    getUserInfo().then(res => {
      if(res.data.code == 0){
        //如果登录放行
        next()
      }else{
        //如果没登录返回首页
        next('/')
        alert('请先登录')
      }
    })
  //  如果不需要登录直接放行
  }else{
    next()
  }

})

 

推荐阅读