Vue 路由拦截

2018-02-17  本文已影响105人  烫嘴豆腐

路由拦截应用场景

图片.png
图片.png

如图所示,当我们进入一个webapp时,点到我的,表示进入个人中心,但是此时用户是首次使用的话,他是没有登录,这时候是不能直接跳转到个人中心页面的。我们希望他去登录页面登录以后在进行操作,这时就需要用到路由拦截。vue文档中称为导航守卫

具体使用

首先在路由定义时加入requireAuth:true

{
    path: '/systemNews',
    component: SystemNews,
    meta: {
      title:'系统消息',
      requireAuth: true //加在这里
    }
  }

配置好路由之后,使用vue导航守卫

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requireAuth)) {
      //if (store.state.token) {
      //  next();
      //}
      if (isLogin) {
          next();
      }else {
          next({
              path: '/login',
              query: {redirect: to.fullPath}
          })
      }
  }else {
      next();
  }
})
to.matched.some(record => record.meta.requireAuth) 
这个表示如果你在定义路由的时候requireAuth为ture则进行路由拦截

代码很简单,能直白的看出功能,isLogin表示用户是否登录,如果登录通过验证,就next()继续路由跳转,如果没有通过验证就跳转到登录页面,并且附加上要跳转的地址query: {redirect: to.fullPath},以便登录后能自动会跳到原本要跳转的路由,也算小小的用户体验。当然你如果喜欢可用vuex来验证也行。

上一篇下一篇

猜你喜欢

热点阅读