vue-router 導航鉤子

vue-router 提供的導航鉤子主要用來攔截導航,讓它完成跳轉取消vue

全局鉤子

  1. router.beforeEach 註冊一個全局的 before 鉤子:vue-router

const router = new VueRouter({ ... })

router.beforeEach((to, from, next) => {
  // ...
})

每一個鉤子方法接收三個參數:瀏覽器

  • to: Route: 即將要進入的目標 路由對象app

  • from: Route: 當前導航正要離開的路由函數

  • next: Function: 必定要調用該方法來 resolve 這個鉤子。執行效果依賴 next 方法的調用參數。
    next(): 進行管道中的下一個鉤子。若是所有鉤子執行完了,則導航的狀態就是 confirmed (確認的)。
    next(false): 中斷當前的導航。若是瀏覽器的 URL 改變了(多是用戶手動或者瀏覽器後退按鈕),那麼 URL 地址會重置到 from 路由對應的地址。
    next('/') 或者 next({ path: '/' }): 跳轉到一個不一樣的地址。當前的導航被中斷,而後進行一個新的導航。eslint


2.afterEach同理,只是不用傳入next函數code


示例:一個單頁面應用,返回首頁時,保存其在首頁的瀏覽位置。而且給每個頁面title賦值

const router = new VueRouter({
  base: __dirname,
  routes
});

new Vue({ // eslint-disable-line
  el: '#app',
  render: h => h(App),
  router
});

let indexScrollTop = 0;
router.beforeEach((route, redirect, next) => {
  if (route.path !== '/') {
    indexScrollTop = document.body.scrollTop;
  }
  document.title = route.meta.title || document.title;
  next();
});

router.afterEach(route => {
  if (route.path !== '/') {
    document.body.scrollTop = 0;
  } else {
    Vue.nextTick(() => {
      document.body.scrollTop = indexScrollTop;
    });
  }
})
相關文章
相關標籤/搜索