1. 程式人生 > 實用技巧 >vue路由鉤子攔截器beforeEach和afterEach及頁面路由變化路由監聽

vue路由鉤子攔截器beforeEach和afterEach及頁面路由變化路由監聽

轉自:https://blog.csdn.net/ddr66288/article/details/102119947?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.compare&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.compare

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

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

總體來講vue裡面提供了三大類鉤子,兩種函式 1、全域性鉤子 2、某個路由的鉤子 3、元件內鉤子

兩種函式:

1. router.beforeEach(function(to,form,next){}) /*在跳轉之前執行*/

2. router.afterEach(function(to,form)}{}) /*在跳轉之後判斷*/
全域性鉤子函式

顧名思義,它是對全域性有效的一個函式

// router.js

const router = new Router({ routes: [ { path: '/', name: 'sideBar', component: sideBar, children:[ { path:'/', name:'sort', component:sort }, { path:'/addNewSort', name:'addNewSort', component:addNewSort }, { path:'/notSend', name:'notSend', component:notSend }, { path:'/sended', name:'sended', component:sended }, } ] }) router.beforeEach((to,from,next)=>{ // console.log("to:",to); // router即將進入的路由物件 // console.log("from:",from); // 當前導航即將離開的路由 // console.log("next:",next); // Function,進行管道中的一個鉤子,如果執行完了,則導航的狀態就是 confirmed (確認的);否則為false,終止導航。 if(to.name=='notSend'){ next({ name:'sort' }) return } next() }) export default router
某個路由的鉤子函式

顧名思義,它是寫在某個路由裡頭的函式,本質上跟元件內函式沒有區別。

// router.js

const router = new VueRouter({
  routes: [
    {
      path: '/login',
      component: Login,
      beforeEnter: (to, from, next) => {
        // ...
      },
      beforeLeave: (to, from, next) => {
        // ...
      }
    }
  ]
})
路由元件的鉤子

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

// *.vue

beforeRouteEnter beforeRouteUpdate (2.2 新增) beforeRouteLeave

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

beforeRouteLeave(to, from, next) {
    next()
},
beforeRouteEnter(to, from, next) {
    next()
},
beforeRouteUpdate(to, from, next) { // 用於相同路由元件的的引數更新
    next()
},
data:{},
method: {}