vue-router,利用router.beforeEach未登录跳转到登录页

vue-router提供了导航钩子,我们使用全局的钩子,在进入页面前判断是否登录

全局钩子

你可以使用 router.beforeEach 注册一个全局的 before 钩子:

const router = new VueRouter({ ... })

router.beforeEach((to, from, next) => {
  // ...
})
当一个导航触发时,全局的 before 钩子按照创建顺序调用。钩子是异步解析执行,此时导航在所有钩子 resolve 完之前一直处于 等待中。

每个钩子方法接收三个参数:

to: Route: 即将要进入的目标 路由对象

from: Route: 当前导航正要离开的路由

next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。

next(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。

next(false): 中断当前的导航。如果浏览器的 URL 改变了(可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。

next('/') 或者 next({ path: '/' }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。

确保要调用 next 方法,否则钩子就不会被 resolved。

同样可以注册一个全局的 after 钩子,不过它不像 before 钩子那样,after 钩子没有 next 方法,不能改变导航:

router.afterEach(route => {
  // ...
})

实例

router.beforeEach((to, from, next) => {
      // 导航钩子,全局钩子
    localStorage.setItem('user','user');
      var user = localStorage.getItem('user');
      if(!user){
              if(to.name != 'Login' && to.name != 'Signin' && to.name != 'Register'){
                    !!user ? next() : next('/login');
              }else{
                    next();
              }
      }else{
            next();
      }
})

你可能感兴趣的:(vue-router,利用router.beforeEach未登录跳转到登录页)