vue3 vue-router 导航守卫 (五)

在Vue 3中,导航守卫仍然是一个重要的概念,用于在路由切换时执行一些特定的逻辑。Vue Router提供了多个导航守卫,包括全局守卫、路由独享守卫和组件内守卫。可以在路由切换时执行一些特定的逻辑,例如身份验证、权限控制、数据加载等帮助你更好地控制整个应用程序的导航流程。

一、全局前置守卫

全局前置守卫会在路由切换之前被调用,并且在所有路由切换中都会被触发

router.beforeEach((to, from, next) => {
  // 在这里执行你的逻辑
  // 通过调用next()来继续路由切换,或者调用next(false)取消路由切换
})

二、路由独享守卫

你也可以为特定的路由定义守卫

const routes = [
  {
    path: '/example',
    component: ExampleComponent,
    beforeEnter: (to, from, next) => {
      // 在这里执行你的逻辑
      // 通过调用next()来继续路由切换,或者调用next(false)取消路由切换
    }
  }
]

三、全局后置守卫

全局后置守卫会在路由切换之后被调用,并且在所有路由切换中都会被触发

router.afterEach((to, from) => {
  // 在这里执行你的逻辑
})

四、组件内守卫

组件内守卫是针对特定组件的守卫,组件内守卫有3个

注意:beforeRouteEnter在setup语法糖中是无法使用的,需要再起一个script标签 使用defineComponent方式来使用

<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
   beforeRouteEnter(to, from, next) {
    // 在这里执行你的逻辑
    // 通过调用next()来继续路由切换,或者调用next(false)取消路由切换
  },
  beforeRouteUpdate(to, from, next) {
    // 在这里执行你的逻辑
    // 通过调用next()来继续路由切换,或者调用next(false)取消路由切换
  },
  beforeRouteLeave(to, from, next) {
    // 在这里执行你的逻辑
    // 通过调用next()来继续路由切换,或者调用next(false)取消路由切换
  }
});
</script>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
</script>

五、案例

下面是一个简单的案例,当我们线上考试时,若通过更改浏览器网址到其他地方而没有到交卷页则提醒你正在考试,是否放弃考试。这个时候我们就可以使用组件内守卫来进行逻辑处理。当然,下面的案例只是提供一个简单的组件内守卫适用场景,代码比较粗糙,具体还需要根据项目情况来处理。

<script setup lang="ts">
import { useRoute,useRouter } from "vue-router";
const router = useRouter();
 const back = async()=>{
      try {
        await this.$confirm("你正在考试,是否放弃考试", "确认信息", {
          distinguishCancelAndClose: true,
          confirmButtonText: "确定",
        });
        try {
          // await this.toTestResult(true)
        } catch (e) {
          router.push({ name: "Home" });
        }
      } catch (e) {
        return false;
      }
    }
</script>

<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
  beforeRouteEnter(to, from, next) {
    //没有跳到交卷页面提醒
    if (to.path != "result") {
      back();
    } else {
      next();
    }
  },
  beforeRouteUpdate(to, from, next) {
    // 在这里执行你的逻辑
    // 通过调用next()来继续路由切换,或者调用next(false)取消路由切换
  },
  beforeRouteLeave(to, from, next) {
    // 在这里执行你的逻辑
    // 通过调用next()来继续路由切换,或者调用next(false)取消路由切换
  },
  
});
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值