vue 路由拦截

路由钩子函数beforeEach 使用方法

* 登陆功能时使用的

// 页面刷新时,重新赋值token
if (sessionStorage.getItem('token')) {
  store.commit('set_token', sessionStorage.getItem('token'))
}


const  router = new Router({
  mode:'history',
  routes: [
    {
      path: '/',
      redirect:'/realtime'
    },
    {
      path:'/login',
      name:'login',
      component:Login,
      meta: {
        requireAuth: false,  // 添加这个字段 并赋值  不需要登陆
      }
    },
    {
      path:'/alarm',
      name:'alarm',
      component:Alarm,
      meta: {
        requireAuth: true,  // 进入这个路由是需要登录
      },
    }]
  }


router.beforeEach((to, from, next) => {
  // console.log("to--fullPath--",to.fullPath)  //路由名称
  if (to.matched.some(r => r.meta.requireAuth)) {  //需要登陆 //这里的requireAuth为路由中定义的 meta:{requireAuth:true},意思为:该路由添加该字段,表示进入该路由需要登陆的
      if (store.state.tokens) {    //token存在   继续
        next();
      } else {                     //token 不存在  返回登陆
        next({
          path: '/login',
          query: {redirect: to.fullPath}
        })
      }
  }else{      //不需要登陆
      next();
  }
})

猜你喜欢

转载自blog.csdn.net/qq_42842709/article/details/82079883