1. 程式人生 > >【vue】router的beforeEach與afterEach鉤子函式

【vue】router的beforeEach與afterEach鉤子函式

在路由跳轉的時候,我們需要一些許可權判斷或者其他操作。這個時候就需要使用路由的鉤子函式。

定義:路由鉤子主要是給使用者在路由發生變化時進行一些特殊的處理而定義的函式。

總體來講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"
    }
]

在子元件中呼叫路由的鉤子函式時無效的。

在官方文件上是這樣定義的:

可以在路由元件內直接定義以下路由導航鉤子

beforeRouteEnter
beforeRouteUpdate (2.2 新增)
beforeRouteLeave

這裡簡單說下鉤子函式的用法:它是和data,methods平級的。

beforeRouteLeave(to, from, next) {
    next()
},
beforeRouteEnter(to, from, next) {
    next()
},
beforeRouteUpdate(to, from, next) {
    next()
},
data:{},
method: {}