vue之路由导航守卫-全局前置守卫

一、使用方式

全局前置守卫用于在路由配置生效之前进行一些动作,可以使用 router.beforeEach 注册一个全局前置守卫:

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

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

参数:        

  • to: Route: 即将要进入的目标 路由对象
  • from: Route: 当前导航正要离开的路由
  • next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。

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

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

    (3)next('/') 或者 next({ path: '/' }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。你可以向 next 传递任意位置对象,且允许设置诸如 replace: true、name: 'home' 之类的选项以及任何用在 router-link 的 to prop 或 router.push 中的选项。

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

二、实例

在进入除登录页的其它页面时常常需要判断是否存在token如果存在则可以访问,如果没有需要返回到登录页,先进性登录获取token,此时可以利用前置守卫进行这个工作:

在router文件夹的index.js路由文件中:

//路由导航守卫
router.beforeEach((to, from, next) => {
  //to 要去的路由配置
  //from 当前的路由配置
  //next 一定要调用,让to的路由配置继续生效,比如如果去登陆直接next(),否则判断token是否存在,如果存在就next()

  if (to.path === '/login') return next() ;//使用return,不需要写else

  //判断其他页面是否有token
  const token = localStorage.getItem('token');

  //存在继续往后走
  if (token) return next();


  // this.$router.push({name:'login'}) #没有this,无法使用
  Message.warning('未登录,请先登录!')
  router.push({
    name: 'login'
  })


});

这样无需在每一个url对应的组件中进行判断token,避免繁琐,如果在每一个组件中使用需要在每一个组件中的beforecreate方法中使用,比如在home组件中:

    //路由导航守卫无需再写这个方法
    beforeCreate() {
      const token = localStorage.getItem('token');
      if (!token) {
        this.$router.push({name: 'login'})
      }
    },

参考:https://router.vuejs.org/zh/guide/advanced/navigation-guards.html#%E5%85%A8%E5%B1%80%E5%89%8D%E7%BD%AE%E5%AE%88%E5%8D%AB

                                                                                                                                                                                                                            

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          

猜你喜欢

转载自www.cnblogs.com/shenjianping/p/11458261.html