在做vue我的项目的时候,要求用户在页面拜访前先登录,或在来到页背后收回揭示。vue官网提供的路由管理器 vue-router 提供的导航钩子,通过跳转或勾销的形式守卫导航。以下总结了路由钩子函数的应用办法和一些应用场景。

一、全局守卫

  • router.beforeEach 路由扭转前的钩子

    const router = new VueRouter({ ... })router.beforeEach((to, from, next) => {    ... ...})

    其中:

    • to:将要拜访的门路
    • from:代表从哪个门路跳转来的
    • next:是一个函数,示意放行。有如下几种调用形式

      • next():如果一起失常,则调用该办法进入下一个钩子;
      • next(false):中断以后导航,即路由地址不发生变化;
      • next('/xxx') 或 next({path: '/xxx'}):强制跳转到指定门路;
      • next(error):如果传入的是一个Error实例,则导航会被中断且该谬误会被传递给 router.onError() 注册过的回调。
    • 应用:

      • 应用该函数,肯定要调用 next(),否则钩子函数不能 resolve;
      • 该办法比拟罕用于:验证用户拜访权限。
        比方:一个零碎须要先验证用户是否登录,如果登录了就能够拜访,否则间接跳转到登录页面。具体实现如下:
      import Vue from 'vue'import VueRouter from 'vue-router'import { getToken } from '@Utils/session.utils' // 登录用户的tokenimport Login from '../pages/Login.vue' //引入登录页const Home = () => import('../pages/Home.vue')  //引入首页Vue.use(VueRouter) // 全局注入router// 配置路由参数const routes = [  { path: '/login', name: 'login', component: Login },  { path: '/home', name: 'home', component: Home }]const router = new VueRouter({  routes})// 全局挂载路由导航守卫:验证用户是否登录router.beforeEach((to, from, next) => {  if (to.name !== 'login' && !getToken()) next('/login') // 如果用户不是拜访登录页且没有登录,则强制跳转到登录页  else next()})export default router
  • router.beforeResolve 在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,该钩子函数就被调用。

    该办法我在我的项目中临时还未应用到,具体应用场景欢送大家补充 :)

  • router.afterEach 路由扭转后的钩子

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

    该办法同全局前置守卫 router.beforeEach 不同的是少了 next() 函数,也不会扭转导航自身。

    应用场景:

    • 路由切换,将页面的滚动地位返回到顶部。

      例如:一个页面比拟长,当滚动到某个地位后切换路由,这时跳转的页面滚动条地位默认是前一个页面来到时停留的地位,能够通过该钩子函数将滚动条地位重置。

      // 切换路由,页面返回到顶部router.afterEach((to, from) => {    window.scrollTo(0, 0)})

二、路由独享的守卫

  • beforeEnter 对某个路由的独自守卫,在路由配置上间接定义

    const routes = [    { path: '/login', name: 'login', component: Login },    {         path: '/home',         name: 'home',         component: Home,        beforeEnter: (to, from, next) => {            ... ...        }    }]const router = new VueRouter({  routes})

    应用:

    • 该办法的参数应用同全局前置守卫 router.beforeEach 是一样的;
    • 例如:依据登录用户的不同角色,展现不同的模块;或者给指定路由组件独自增加动画。
    import Vue from 'vue'import VueRouter from 'vue-router'import { getUserRole } from '@Utils/session.utils' // 登录用户的角色const UserCenter = () => import('../pages/UserCenter.vue')const routes = [    ... ...    {         path: '/usercenter',         name: 'usercenter',         component: UserCenter,        beforeEnter: (to, from, next) => {            if(getUserRole() === 'admin') next('/admincenter')            else next()        }    }]

三、组件内的守卫

  • beforeRouteEnter(to, from, next) 在进入以后组件对应的路由前调用

    export default {    data() { ... },    beforeRouteEnter(to, from, next) {        ... ...    }}

    留神:

    • 该函数内不能拜访以后组件实例 this,因为函数在对应路由被 comfirm 前调用,此时将要渲染的组件实例还没被创立;
    • 能够通过给 next 传递一个回调来拜访组件实例,即把组件实例 vm 作为回调办法的参数;该回调的执行在 mounted 前面;

      beforeRouteEnter (to, from, next) {    next(vm => {        // 通过 vm 来拜访组件实例    })}
    • beforeRouteEnter 是反对给 next 传递回调的惟一守卫。
    • 应用场景:
      例如:从一个列表页进入到详情页,而后再返回到列表页,要求保留来到列表页之前拜访的数据及滚动地位,从其余页面从新进入列表页,获取最新的数据。具体实现请点这里
  • beforeRouteUpdate(to, from, next) 在以后路由扭转,然而该组件被复用时调用

    beforeRouteUpdate (to, from, next) {    ... ...}

    注:

    • 该函数内能够拜访以后组件实例 this
    • 例如:在一个带有动静参数的门路 /detail/:id,在 /detail/aaa/detail/bbb 之间跳转的时候,因为两个路由渲染的是同个 Detail 组件,因而原来的组件实例会被复用(比起销毁再创立,复用则会更加高效),在这种状况下这个钩子会被调用,而组件的生命周期钩子不会再被调用。
  • beforeRouteLeave(to, from, next) 在来到以后组件对应的路由前调用

    beforeRouteLeave (to, from, next) {    ... ...}

    注:

    • 该函数内能够拜访以后组件实例 this;
    • 比方:用户在以后页面有还未保留的内容时忽然来到,阻止页面跳转并给出提醒,或者在用户来到时革除或存储一些信息等。

四、残缺的导航解析流程

  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 的回调函数,创立好的组件实例会作为回调函数的参数传入。

其实罕用的也就那么几个,了解了其用法,路由导航的解析流程也就明了了。

五、附:应用 watch 监测路由变动

除了应用钩子函数外,咱们也能够应用 watch 来监听 $route 对象,而后依据路由参数的变动来进行响应。

<template>    <div id=``"app"``>        <keep-alive>            <router-view/>        </keep-alive>    </div></template><script>    export default {        name: 'App',        watch: {            '$route' (to, from) {                // 对路由变动作出响应...            }        }    }</script>