在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>