LQ博客 www.lqblogs.com
arrows
nav

用beforeRouteLeave独享守卫钩子函数做路由过滤

作者:lq 来源:原创 发布时间:2019-08-29 浏览量:5752 评论:0 点赞:2

在使用beforeRouteLeave独享守卫钩子函数做路由过滤之前,我们首相讲解下该函数使用的一些基础,和使用该函数的需求场景。

beforeRouteLeave带有三个参数,分别是to,from,next

    to(指向目的地的对象信息)

    from(指向来源对象信息)

    next(继续向下走)(next(true), next()都是正常向下走,next(false)停止向下走)


注意:beforeRouteLeave只对内部路由约束

          外部链接是不受约束的

          当前路由刷新也不受约束


其实,在很多项目中,当页面离开的时候,我们会遇到各色各样的需求,下面我总结下我最常见遇到的需求:

    1.缓存当前页面数据
    2.清除当前页面缓存数据

    3.拦截跳转


页面离开的方式,一般分为两种:

    1.指向性离开(触发固定式的链接而离开)

    2.非指向性离开(物理返回或关闭离开)


示例demo,仅供参考

<template>
  <div class="test-box">
    <p @click="go(1)">点击跳到内部HelloWorld</p>
    <p @click="go(2)">点击跳到内部HelloWorld2</p>
    <p @click="go(3)">点击跳到外部百度</p>
  </div>
</template>
<script>
export default {
  name:'test',
  data() {    
    return {
      interceptLeave:0,//(0正常离开,1拦截) 
    }
  },
  methods: {
    go(type){ 
      switch (type) {
        case 1: this.$router.push({ name: 'HelloWorld' });
                break;
        case 2: this.interceptLeave = 1;
                this.$router.push({ name: 'HelloWorld2' });
                break;
        case 3: location.href = 'https://www.baidu.com';//外部链接,不受beforeRouteLeave约束
                break;
      }
    }
  },
  beforeRouteLeave(to, from, next){
     let self = this;
     console.log(self.interceptLeave)
     if(self.interceptLeave){
       next(false);
     }else{
        next();
     }
  }
}
</script>

<style scoped>
  .test-box{
      width:100%;
      height:auto;
      padding:0;
      margin: 0 auto;
      text-align: center;
      font-size: 20px;
      display: block;
  }
</style>
beforeRouteLeave Vue
如果你感觉本文章对你有帮助的话,那就点赞、打赏或订阅一下吧
点赞(2)
打赏
倒踩(0)
关闭 感谢您的支持,我会继续努力
微信支付
支付宝支付
扫码打赏,建议金额1-20元
浏览量(5752)
讨论本篇文章(0)
发表评论

最多访问文章

最新文章