Vue 路由守衛(wèi)(導(dǎo)航鉤子函數(shù))

1. 路由守衛(wèi)(導(dǎo)航鉤子函數(shù))

1.1 beforeEach: 全局前置守衛(wèi)

const router = new VueRouter({}) 

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

1.2 beforeEnter: 路由獨(dú)享的守衛(wèi)(路由內(nèi)鉤子)

routes: [
  {
    path: '/person',
    component: () => import(''),
    beforeEnter: (to, from, next) => { }       
  }
]

2. 組件內(nèi)的守衛(wèi)(組件內(nèi)鉤子)

2.1 beforeRouteEnter

beforeRouteEnter (to, from, next) { 
  // 在渲染該組件的對(duì)應(yīng)路由被 confirm 前調(diào)用 
  // 不能獲取組件實(shí)例 this
  // 因?yàn)楫?dāng)守衛(wèi)執(zhí)行前,組件實(shí)例還沒被創(chuàng)建 
}

不過,可以通過傳一個(gè)回調(diào)給 next來訪問組件實(shí)例。在導(dǎo)航被確認(rèn)的時(shí)候執(zhí)行回調(diào),并且把組件實(shí)例作為回調(diào)方法的參數(shù)。

beforeRouteEnter (to, from, next) {
  next(vm => {
    // 通過 `vm` 訪問組件實(shí)例
  })
}

2.2 beforeRouteUpdate

beforeRouteUpdate(to, from, next) {
  // 在當(dāng)前路由改變,或者該組件被復(fù)用時(shí)調(diào)用
  // 舉例來說,對(duì)于一個(gè)帶有動(dòng)態(tài)參數(shù)的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉(zhuǎn)的時(shí)候, 
  // 由于會(huì)渲染同樣的 Foo 組件,因此組件實(shí)例會(huì)被復(fù)用。而這個(gè)鉤子就會(huì)在這個(gè)情況下被調(diào)用。
  // 可以訪問組件實(shí)例 this
}

2.3 beforeRouteLeave

beforeRouteLeave(to, from, next) {
  // 導(dǎo)航離開該組件的對(duì)應(yīng)路由時(shí)調(diào)用 
  // 可以訪問組件實(shí)例 this
}

應(yīng)用場(chǎng)景:

2.3.1 清除當(dāng)前組件中的定時(shí)器
// 當(dāng)一個(gè)組件中有一個(gè)定時(shí)器時(shí), 在路由進(jìn)行切換的時(shí)候, 可使用 beforeRouteLeave 將定時(shí)器進(jìn)行清除, 以免占用內(nèi)存(可以用 destroyed 生命周期鉤子函數(shù)代替)
beforeRouteLeave(to, from, next) {
  clearInterval(this.timer);
  next()
}
2.3.2 當(dāng)頁面中有未關(guān)閉的窗口,或未保存的內(nèi)容時(shí),,阻止頁面跳轉(zhuǎn)
beforeRouteLeave(to, from, next) {
  if (this.isShow) {
    alert('必須關(guān)閉彈窗才能跳轉(zhuǎn)頁面');
    next(false);
  } else {
    next();
  }
}
2.3.3 保存相關(guān)內(nèi)容到Vuex中或Session中(可以用destroyed生命周期鉤子函數(shù)代替)
beforeRouteLeave(to, from, next) {
  sessionStorage.setItem(name, content); // 保存到sessionStorage中
  next()
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容