路由守衛(wèi)beforeEach,beforeResolve,afterEach

index.js
router.beforeEach((to, from, next) => {
  console.log('before each invoked');
  if (to.fullPath === '/app') {
    // next('/login')//不僅可以寫字符串還可以是一個對象
    next({path: '/login', replace})
  } else {
    next()
  }
});
router.beforeResolve((to, from, next) => {
  console.log("before resolve invoked")
  next();
});
router.afterEach((to, from) =>{
  console.log("after invoked")
})

路由守衛(wèi)常用于路由跳轉(zhuǎn)判斷是否需要登錄等,如果需要就跳轉(zhuǎn)到登錄頁面

vue的另外一個鉤子函數(shù) beforeEnter

在routes.js(路由)里面設(shè)置
export default [
  {
    path: '/login',
    component: Login,
    name: 'login',
    // 進入Login頁面前執(zhí)行的鉤子函數(shù)
    beforeEnter (to, from, next) {
      console.log("Loginroute before enter")
      next();
    },
  },
]

用于組件內(nèi)部的鉤子

export default{
//  從另外的組件進入該組件前觸發(fā)該鉤子
beforeRouteEnter(to, from, next) {
    console.log("todo before enter");
    console.log(this) // 這里獲取不到上下文
    next(vm => { // next里面有一個回到函數(shù)可以獲取到上下文,把請求到的數(shù)據(jù)塞到vue對象中
      console.log(vm.id)
      console.log(vm.msg)
      vm.test();
    });
  },
//  同一個組件,param不同的是觸發(fā),常用與同一個組件當(dāng)傳入不通參數(shù)時,展示不同的數(shù)據(jù)
  beforeRouteUpdate(to, from, next){
    console.log("todo update enter")
    next();
  },
//  該組件離開跳轉(zhuǎn)到另外的組件時觸發(fā)該鉤子,常應(yīng)用于用戶表單,當(dāng)用戶填了一部分內(nèi)容,需要提醒用戶是否離開頁面
 beforeRouteLeave(to, from, next){
    console.log("todo leave enter")
    if(global.confirm('are you sure')){
      next();
    }
  },
  data(){
     return{
  }
}
}
特別注意:beforeRouteUpdate的觸發(fā)條件
image.png

image.png

當(dāng)從app123,跳轉(zhuǎn)到app456的時候就會觸發(fā)beforeRouteUpdate

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 組件相關(guān)鉤子函數(shù): beforeCreate、created、beforeMount、mounted、before...
    744354889606閱讀 19,268評論 0 37
  • 一:什么是閉包?閉包的用處? (1)閉包就是能夠讀取其他函數(shù)內(nèi)部變量的函數(shù)。在本質(zhì)上,閉包就 是將函數(shù)內(nèi)部和函數(shù)外...
    xuguibin閱讀 10,016評論 1 52
  • 原文鏈接:https://github.com/halfrost/Halfrost-Field/blob/mast...
    hament閱讀 5,809評論 1 31
  • vue-cli搭建項目 確保安裝了node與npm 再目標(biāo)文件夾下打開終端 執(zhí)行cnpm i vue-cli -g...
    Akiko_秋子閱讀 3,354評論 1 22
  • 在使用 Vue 或者 Angular 的時候,框架提供了路由守衛(wèi)功能,用來在進入某個路有前進行一些校驗工作,如果校...
    柏丘君閱讀 34,828評論 12 32

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