vue-router的钩子函数

前言

路由钩子函数有3个参数

to:表示路由要去哪里(是一个对象类型)

from:表示路由从哪里来(是一个对象类型)

next:next()执行管道中的下一个钩子;next(false)中断导航,浏览器的地址会重置到from地址;next({path:"/'})跳转到path路径对应的地址,该方法在afterEach钩子函数中不存在

路由钩子函数可分为2类:全局类和局部类

全局类

全局类就是针对整个路由的操作,每次跳转都会执行全局类的钩子函数

全局前置守卫beforeEach

进入路由之前,执行的方法,通常做的就是在这里验证是否登录,没有登录就返回.

这里要注意next指定路径的时候需要做判断,以免死循环

var router = new VueRouter({
      routes: [
        {
          path: "/login",
          component: {
            template: `<div>login page</div>`
          }
        },
        {
          path: '/position',
          component: position,
          meta: {
            auth: true
          }
        },
        {
          path: '/search/:keyword',
          component: search
        }
      ]
    }) 
router.beforeEach((to, from, next) => {
      console.log('beforeEach', to, from)
      // //....
      //islogin的判断就是为了防止死循环
      if (!islogin && to.meta.auth) {
        islogin = true;
        next({
          path: '/login'
        });
      } else {
        next();
      }
    })

全局解析守卫beforeReslove

在导航确认之前,同时在所有组件内守卫和异步路由组件解析完之后调用

全局后置钩子afterEach

该钩子函数特殊的是没有next方法,只有to和from

在路由跳转成功后执行该函数

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

局部类

路由独享守卫beforeEnter

写在路由配置表中的配置项,表示当前路由进入之前.和beforeEach类似,但是beforeEach针对所有路由进入前,而beforeEnter只针对某一个路由进入前

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        // ...
      }
    }
  ]
})

组件内的守卫

beforeRouteEnter

在进入当前模块之前的函数,我们可以通过它来确定是否进入当前模块

const Foo = {
  template: `...`,
  beforeRouteEnter (to, from, next) {
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不!能!获取组件实例 `this`
    // 因为当守卫执行前,组件实例还没被创建
  }
}

beforeRouteUpdate

当组件没有经历创建和销毁,仅仅是路由参数有更新的时候执行该函数

比如我们路由是这样定义的:path:“user/:id",当id改变的时候,就是一种路由参数现象.beforeRouteUpdate会执行

下面这个例子,我们点击di1和di2会导致keyword改变,就会触发beforeRouteUpdate

 <router-link tag="li" to="/search/fe" active-class="active">搜索di1</router-link>
 <router-link tag="li" to="/search/be" active-class="active">搜索di2</router-link>
 <router-view></router-view>
const search = {
      template: `<div>search</div>`,
      beforeRouteUpdate(to, from, next) {
        console.log('beforeRouteUpdate:', to)
      }
}

var router = new VueRouter({
        {
          path: '/search/:keyword',
          component: search
        }
      ]
    })

beoreRouteLeave

导航离开该组件时调用的函数

原文地址:https://www.cnblogs.com/liuXiaoDi/p/13068991.html