在路由跳轉的時候,我們需要一些權限判斷或者其他操作。這個時候就需要使用路由的鈎子函數。
定義:路由鈎子主要是給使用者在路由發生變化時進行一些特殊的處理而定義的函數。
總體來講vue里面提供了三大類鈎子,兩種函數
1、全局鈎子
2、某個路由的鈎子
3、組件內鈎子
兩種函數:
1、Vue.beforeEach(function(to,form,next){}) /*在跳轉之前執行*/
2.Vue.afterEach(function(to,form))/*在跳轉之后判斷*/
全局鈎子函數
顧名思義,它是對全局有效的一個函數
1
2
3
4
5
6
|
router.beforeEach((to, from, next) => {
let token = router.app.$storage.fetch("token");
let needAuth = to.matched.some(item => item.meta.login);
if(!token && needAuth) return next({path: "/login"});
next();
});
|
beforeEach函數有三個參數:
- to:router即將進入的路由對象
- from:當前導航即將離開的路由
- next:Function,進行管道中的一個鈎子,如果執行完了,則導航的狀態就是 confirmed (確認的);否則為false,終止導航。
afterEach函數不用傳next()函數
某個路由的鈎子函數
顧名思義,它是寫在某個路由里頭的函數,本質上跟組件內函數沒有區別。
const router = new VueRouter({ routes: [ { path: '/login', component: Login, beforeEnter: (to, from, next) => { // ... }, beforeLeave: (to, from, next) => { // ... } } ] })
路由組件的鈎子
注意:這里說的是路由組件!
路由組件 屬於 組件,但組件 不等同於 路由組件!所謂的路由組件:直接定義在router中component處的組件。如:
var routes = [ { path:'/home', component:home, name:"home" } ]
在子組件中調用路由的鈎子函數時無效的。
在官方文檔上是這樣定義的:
可以在路由組件內直接定義以下路由導航鈎子
beforeRouteEnter
beforeRouteUpdate (2.2 新增)
beforeRouteLeave
這里簡單說下鈎子函數的用法:它是和data,methods平級的。
beforeRouteLeave(to, from, next) { next() }, beforeRouteEnter(to, from, next) { next() }, beforeRouteUpdate(to, from, next) { next() }, data:{}, method: {}