vue组件导航守卫函数详解 beforeRouteEnter/beforeRouteUpdate/beforeRouteLeave

Vue导航守卫beforeRouteEnter、beforeRouteUpdate、beforeRouteLeave三个函数。以我自己的理解就是监听页面进入,修改,和离开的功能。
每个守卫接受三个参数:

to: Route: 即将要进入的目标路由对象
from: Route: 当前导航正要离开的路由
next: Function:一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
next():进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。
next(false):中断当前的导航。如果浏览器的 URL 改变了(可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。

next(’/’) 或者 next({ path: ‘/’ }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。

next(error): (2.4.0+) 如果传入 next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给
router.onError() 注册过的回调。

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

test组件


<template>
  <div class="test_box">
    <p @click="go">测试组件内部守卫的作用,点击跳到HelloWorld</p>
  </div>
</template>
<script>
export default {
  data() {
    return {

    }
  },
  methods: {
    go() {
      this.$router.push({ name: 'HelloWorld' })
    }
  },
  **beforeRouteEnter(to, from, next)** {
    console.log(this, 'beforeRouteEnter'); // undefined
    console.log(to, 'beforeRouteEnter第一个参数');
    console.log(from, 'beforeRouteEnter第二个参数');
    console.log(next, 'beforeRouteEnter第三个参数');
    next(vm => {
      //因为当钩子执行前,组件实例还没被创建
      // vm 就是当前组件的实例相当于上面的 this,所以在 next 方法里你就可以把 vm 当 this 来用了。
      console.log(vm);//当前组件的实例
    });
  },

  **beforeRouteUpdate(to, from, next)** {
    //在当前路由改变,但是该组件被复用时调用
    //对于一个带有动态参数的路径 /good/:id,在 /good/1 和 /good/2 之间跳转的时候,
    // 由于会渲染同样的good组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    // 可以访问组件实例 `this`
    console.log(this, 'beforeRouteUpdate'); //当前组件实例
    console.log(to, 'beforeRouteUpdate第一个参数');
    console.log(from, 'beforeRouteUpdate卫第二个参数');
    console.log(next, 'beforeRouteUpdate卫第三个参数');
    next();
  },


  **beforeRouteLeave(to, from, next) {**
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
    console.log(this, 'beforeRouteLeave'); //当前组件实例
    console.log(to, 'beforeRouteLeave第一个参数');
    console.log(from, 'beforeRouteLeave第二个参数');
    console.log(next, 'beforeRouteLeave第三个参数');
    next();
  }
}

</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>


</style>

helloworld组件

<template>
  <div class="sider_box">
      <p @click="go">第一个页面</p>
      <p @click="goTest">触发让它跳到test页面检查组件守卫功能</p>
  </div>
</template>
<script>
export default {
  data() {
    return {

    }
  },
  methods: {
    go(){
      this.$router.push({name:'navMenu'})
    },
    goTest(){
      this.$router.push({name:'test'})
    }
  }
}

</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

输出结果:
先从helloword跳到test可以看到控制台打印
在这里插入图片描述
在这里插入图片描述
再从test跳到helloword可以看到打印如下:
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值