在路由跳轉的時候,我們需要一些權限判斷或者其他操作。這個時候就需要使用路由的鉤子函數。
定義:路由鉤子主要是給使用者在路由發生變化時進行一些特殊的處理而定義的函數。
總體來講vue裏面提供了三大類鉤子,兩種函數
1、全局鉤子
2、某個路由的鉤子
3、組件內鉤子
兩種函數:
1. Vue.beforeEach(function(to,form,next){}) /*在跳轉之前執行*/
2. Vue.afterEach(function(to,form))/*在跳轉之後判斷*/
全局鉤子函數
顧名思義,它是對全局有效的一個函數
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"
}
]
在子組件中調用路由的鉤子函數時無效的。
在官方文檔上是這樣定義的:
它是和data,methods平級的。
beforeRouteLeave(to, from, next) {
next()
},
beforeRouteEnter(to, from, next) {
next()
},
beforeRouteUpdate(to, from, next) {
next()
},
data:{},
method: {}
原文地址:https://www.cnblogs.com/WQLong/p/8135553.html