vue 路由Router守卫

完整的导航解析流程

  1. 导航被触发。
  2. 在失活的组件里调用 beforeRouteLeave 守卫。
  3. 调用全局的 beforeEach 守卫。
  4. 在重用的组件里调用 beforeRouteUpdate 守卫 (2.2+)。
  5. 在路由配置里调用 beforeEnter
  6. 解析异步路由组件。
  7. 在被激活的组件里调用 beforeRouteEnter
  8. 调用全局的 beforeResolve 守卫 (2.5+)。
  9. 导航被确认。
  10. 调用全局的 afterEach 钩子。
  11. 触发 DOM 更新。
  12. 调用 beforeRouteEnter 守卫中传给 next 的回调函数,创建好的组件实例会作为回调函数的参数传入。
import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

let router = new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: () => import('../page/home')
    },
    {
      path: '/ads',
      name: 'Ads',
      component: () => import('../page/ads'),

    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('../page/login')
    },

    {
      path: '/detail',
      name: 'Detail',
      component: () => import('../page/detail'),
      // 路由独享守卫
      beforeEnter: (to, from, next) => {
        console.log(to, 'to', from, 'from', 'beforeEnter')
        next()
      }
    },
  ]
})



//全局前置路由守卫
router.beforeEach((to, from, next) => {
  console.log(to, 'to', from, 'from', 1)
  console.log(to.name === 'Ads', from.name == 'Login')
  next()
})

//全局解析守卫
router.beforeResolve((to, from, next) => {
  console.log(to, 'to', from, 'from', 2)
  next()
})


//全局后置钩子
router.afterEach((to, from) => {
  console.log(to, 'to', from, 'from', 3)
})
export default router;
View Code
原文地址:https://www.cnblogs.com/lvlisn/p/14943517.html