vue-router 路由守卫

  • 全局的:进入任何一个路由都会执行
beforeEach(to, from, next):进入路由前执行
// 在渲染该组件的对应路由被 confirm 前调用
// 不!能!获取组件实例 `this`
// 因为当守卫执行前,组件实例还没被创建
beforeResolve(to, from, next):在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,解析守卫就被调用
afterEach(to, from, next):导航确认执行时执行,可理解为导航完成时执行
  • 路由的:进入某个路由才会执行
beforeEnter(to, from, next): 进入该路由前
  • 组件的:进入某个组件才会执行组件复用时
beforeRouteEnter(to, from, next): 进入组件时
beforeRouteUpdate(to, from, next): 组件被复用时调用
beforeRouteLeave(to, from, next): 离开组件前

开发实例:

// 路由守卫
router.beforeEach((to, from, next) => {
  // 判断是否登录
  if ($cookies.get('userToken')) {
    next()
  } else {
    // 如果没有登录,但是跳转登录页面也放行
    if (to.name === 'zhlogin') {
      next()
    } else {
      // 如果没有登录,也不是去登录页,就拦截,让它跳转登录页
      next('/zhlogin')
    }
  }
posted @ 2021-02-23 10:54  张尊娟  阅读(124)  评论(0编辑  收藏  举报