路由鉤子,即導航鉤子,其實就是路由攔截器,vue-router一共有三類:
全局鉤子:最常用
路由單獨鉤子
組件內鉤子
1、全局鉤子
在src/router/index.js中使用,代碼如下:
// 定義路由配置const router = new VueRouter({ ... })// 全局路由攔截-進入頁面前執行router.beforeEach((to, from, next) => { // 這裏可以加入全局登陸判斷 // 繼續執行 next();});// 全局後置鉤子-常用於結束動畫等router.afterEach(() => { //不接受next});export default router;
每個鉤子方法接收三個參數:
to: Route : 即將要進入的目標 [路由對象]
from: Route : 當前導航正要離開的路由
next: Function : 繼續執行函數
next():繼續執行
next(false):中斷當前的導航。
next(‘/‘) 或 next({ path: ‘/‘ }):跳轉新頁面,常用於登陸失效跳轉登陸
2、路由單獨鉤子
使用:在路由配置中單獨加入鉤子,在src/router/index.js中使用,代碼如下:
{ path:'/home/one', // 子頁面1 component: One, // 路由內鉤子 beforeEnter: (to, from, next) => { console.log('進入前執行'); next(); }}
3、組件內鉤子
使用:在路由組件內定義鉤子函數:
beforeRouteEnter:進入頁面前調用
beforeRouteUpdate (2.2 新增):頁面路由改變時調用,一般需要帶參數
beforeRouteLeave:離開頁面調用
任意找一頁面,編寫如下代碼:
<script>export default { name: 'Two', data () { return { msg: 'Hi, I am Two Page!' } }, // 進入頁面前調用 beforeRouteEnter(to, from, next) { console.log('進入enter路由鉤子') next() }, // 離開頁面調用 beforeRouteLeave(to,from, next){ console.log('進入leave路由鉤子') next() }, // 頁面路由改變時調用 beforeRouteUpdate(to, from, next) { console.log('進入update路由鉤子') console.log(to.params.id) next() }}</script>