Vue3路由組件內(nèi)的路由守衛(wèi)onBeforeRouteLeave和onBeforeRouteUpdate使用
更新時間:2024年05月08日 10:39:16 作者:NorthCastle
這篇文章主要介紹了Vue3路由組件內(nèi)的路由守衛(wèi)onBeforeRouteLeave和onBeforeRouteUpdate使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
簡介
組件內(nèi)的路由守衛(wèi),實際上就是兩個 API 方法。
他們與普通的守衛(wèi)不同的是 : 他們是寫在組件內(nèi)的,在組件中監(jiān)聽路由的變化,不是全局的,比較靈活。
以下是兩個 API 的功能說明:
onBeforeRouteLeave()
: 守衛(wèi)在當前路由離開時觸發(fā),例如 :從 /c 跳轉(zhuǎn)到 /aonBeforeRouteUpdate()
: 守衛(wèi)在當前路由發(fā)生改變時觸發(fā),例如 : 從 /c/100 跳轉(zhuǎn)到 /c/200
案例
本案例演示上述兩個 API 的基本使用,沒有太多的邏輯操作。
路由配置
// 導(dǎo)入 定義路由的兩個方法 import {createRouter,createWebHistory} from 'vue-router' // 引入組件 import componentA from "./componentA.vue"; import componentC from "./componentC.vue"; // 聲明路由跳轉(zhuǎn)的路徑與組件的對應(yīng)關(guān)系 const routsList = [ {path:'/a',name:'aroute',component:componentA}, { path:'/c/:id', name:'croute', component:componentC } ] // 創(chuàng)建路由的實例對象 const routerConfigObj = createRouter({ history:createWebHistory('abc'), // 帶一個參數(shù),表示是路由的一個前綴 routes:routsList // 指定路由的配置列表 }) // 導(dǎo)出路由的對象 export default routerConfigObj;
組件C 中的API 使用代碼(核心)
<template> <div class="divb"> 這是組件C <br> <button @click="goToA">跳轉(zhuǎn)到組件a</button> <br> <button @click="goToC200">更新到組件c200</button> </div> </template> <script setup lang="ts"> // 引入路由相關(guān)的 API import {useRouter} from 'vue-router'; // 聲明 路由對象和當前路由對象 const routeObj = useRouter() // 點擊按鈕,跳轉(zhuǎn)到組件a const goToA = ()=>{ routeObj.push({ path:'/a' }) } // 更新到組件c 200 const goToC200 = ()=>{ routeObj.push({ path:'/c/200' }) } // 導(dǎo)入兩個組件內(nèi)的路由守衛(wèi)API import { onBeforeRouteLeave,onBeforeRouteUpdate } from 'vue-router'; // 路由離開時的操作 onBeforeRouteLeave((to,from)=>{ console.log('組件c : onBeforeRouteLeave - to :',to); console.log('組件c : onBeforeRouteLeave - from :',from); alert('當前內(nèi)容未保存,是否繼續(xù)離開?') }) // 路由更新時的操作 onBeforeRouteUpdate((to,from)=>{ console.log('組件c : onBeforeRouteUpdate - to :',to); console.log('組件c : onBeforeRouteUpdate - from :',from); alert('即將跳轉(zhuǎn)到 /c/200,請稍等') }) </script> <style scoped> .divb{ width: 200px; height: 100px; background: rgb(23, 177, 182); } </style>
運行效果1:路由跳轉(zhuǎn)
運行效果2:路由更新
總結(jié)
以上就是 組合式API 中的 兩個組件內(nèi)的 路由守衛(wèi)的操作。
這些僅為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
詳解element-ui級聯(lián)菜單(城市三級聯(lián)動菜單)和回顯問題
這篇文章主要介紹了詳解element-ui級聯(lián)菜單(城市三級聯(lián)動菜單)和回顯問題,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起學(xué)習學(xué)習吧2019-10-10vue-router二級導(dǎo)航切換路由及高亮顯示的實現(xiàn)方法
這篇文章主要給大家介紹了關(guān)于vue-router二級導(dǎo)航切換路由及高亮顯示的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,對大家學(xué)習或者使用Vue具有一定的參考學(xué)習價值,需要的朋友們下面來一起學(xué)習學(xué)習吧2019-07-07