Vue:router的beforeEach與afterEach鉤子函數

在路由跳轉的時候,咱們須要一些權限判斷或者其餘操做。這個時候就須要使用路由的鉤子函數。html

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

整體來說vue裏面提供了三大類鉤子,兩種函數
一、全局鉤子
二、某個路由的鉤子
三、組件內鉤子app

兩種函數:函數

一、Vue.beforeEach(function(to,form,next){}) /*在跳轉以前執行*/fetch

2.Vue.afterEach(function(to,form))/*在跳轉以後判斷*/spa

全局鉤子函數

顧名思義,它是對全局有效的一個函數code

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()函數component

某個路由的鉤子函數

顧名思義,它是寫在某個路由裏頭的函數,本質上跟組件內函數沒有區別。orm

const router = new VueRouter({
  routes: [
    {
      path: '/login',
      component: Login,
      beforeEnter: (to, from, next) => {
        // ...
      },
      beforeLeave: (to, from, next) => {
        // ...
      }
    }
  ]
})

路由組件的鉤子

注意:這裏說的是路由組件!router

路由組件 屬於 組件,但組件 不等同於 路由組件!所謂的路由組件:直接定義在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: {}
相關文章
相關標籤/搜索