vue2.0全局路由守卫(全局控制登陆)

例:bash

router.beforeEach((to, from, next) => {
  let isLogin = Vue.prototype.$loginInfo.info.is_login
  if (to.matched.length === 0) { //没有匹配到当前路由
    next('/error')
  } else if (!isLogin && to.path !== '/login' && to.path !== '/register' && to.path !== '/password') {
    //若是没有登陆,跳转到登陆页面
    next('/login')
  } else {
    if ((to.path === '/login' || to.path === '/register' || to.path === '/password' || to.path === '/error') && isLogin) { 
      //若是已经登陆,却尝试访问登陆页面或者错误页面,将继续保持本来的页面
       next(from.path)  
    } else {
      next()
    }
  }
  // next()
})
复制代码

全局后置钩子

你也能够注册全局后置钩子,然而和守卫不一样的是,这些钩子不会接受 next 函数也不会改变导航自己:函数

router.afterEach((to, from) => {
  // ...
})

复制代码

路由独享的守卫

你能够在路由配置上直接定义 beforeEnter 守卫:ui

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        // ...
      }
    }
  ]
})
复制代码
相关文章
相关标签/搜索