Vue Router路由守衛(wèi)超詳細介紹
全局前置&后置路由守衛(wèi)
router/index.js
import Vue from 'vue'; import VueRouter from 'vue-router'; import List from '@/pages/List' Vue.use(VueRouter); const router = new VueRouter({ routes: [{ path: '/list', component: List, meta: { // 路由元數(shù)據(jù) title: '列表' ... // 可自定義配置參數(shù) } }] }); // 前置:在路由切換之前調用 router.beforeEach((to, from, next) => {}); // 后置:在路由切換成功之后調用 router.afterEach((to, from) => {}); export default router;
說明
① router.beforeEach()
是全局前置路由守衛(wèi)
② router.afterEach()
是全局后置路由守衛(wèi)
③ to:目的地路由信息
④ from: 出發(fā)地路由信息
⑤ next:是個函數(shù),只有調用next(),路由器才可繼續(xù)跳轉,不調用直接攔截
⑥ routes中的meta配置項,可配置一些自定義的參數(shù)
獨享路由守衛(wèi)
router/index.js
import Vue from 'vue'; import VueRouter from 'vue-router'; import List from '@/pages/List'; import Detail from '@/pages/Detail'; Vue.use(VueRouter); export default new VueRouter({ routes: [{ path: '/list', component: List, children: [{ path: 'detail', component: Detail, // Detail組件獨享此路由守衛(wèi) beforeEnter: (to, from, next) => {} }] }] });
說明
① 組件內部的beforeEnter()
是獨享前置路由守衛(wèi)
② 獨享路由守衛(wèi)只有前置沒有后置
③ 獨享路由守衛(wèi)與全局路由守衛(wèi)可一起搭配使用
組件內路由守衛(wèi)
Detail組件
<template> <div></div> </template> <script> export default { name: 'Detail', // 通過路由,進入組件之前調用 beforeRouteEnter(to, from, next) {}, // 通過路由,離開組件之前調用 beforeRouteLeave(to, from, next) {} } </script>
說明
① beforeRouteEnter()
,通過路由,進入組件之前被調用
② beforeRouteLeave()
,通過路由,離開組件之前被調用
③ 兩者都需要調用next()放行
到此這篇關于Vue Router路由守衛(wèi)超詳細介紹的文章就介紹到這了,更多相關Vue Router路由守衛(wèi)內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
詳細聊聊前端如何實現(xiàn)token無感刷新(refresh_token)
實現(xiàn)token無感刷新對于前端來說是一項非常常用的技術,其本質是為了優(yōu)化用戶體驗,下面這篇文章主要給大家介紹了關于前端如何實現(xiàn)token無感刷新(refresh_token)的相關資料,需要的朋友可以參考下2022-11-11使用Vue Composition API寫出清晰、可擴展的表單實現(xiàn)
這篇文章主要介紹了使用Vue Composition API寫出清晰、可擴展的表單實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-06-06