vue組件獨享守衛鈎子函數參數詳解(beforeRouteEnter、beforeRouteUpdate、beforeRouteLeave)


一樣的和前面路由鈎子類似的步驟

首先在demo下面的components下面新建一個test.vue組件

test組件代碼

<template>
  <div class="test_box">
    <p @click="go">測試組件內部守衛的作用,點擊跳到HelloWorld</p>
  </div>
</template>
<script>
export default {
  data() {
    return {

    }
  },
  methods: {
    go() {
      this.$router.push({ name: 'HelloWorld' })
    }
  },
  beforeRouteEnter(to, from, next) {
    console.log(this, 'beforeRouteEnter'); // undefined
    console.log(to, '組件獨享守衛beforeRouteEnter第一個參數');
    console.log(from, '組件獨享守衛beforeRouteEnter第二個參數');
    console.log(next, '組件獨享守衛beforeRouteEnter第三個參數');
    next(vm => {
      //因為當鈎子執行前,組件實例還沒被創建
      // vm 就是當前組件的實例相當於上面的 this,所以在 next 方法里你就可以把 vm 當 this 來用了。
      console.log(vm);//當前組件的實例
    });
  },
  beforeRouteUpdate(to, from, next) {
    //在當前路由改變,但是該組件被復用時調用
    //對於一個帶有動態參數的路徑 /good/:id,在 /good/1 和 /good/2 之間跳轉的時候,
    // 由於會渲染同樣的good組件,因此組件實例會被復用。而這個鈎子就會在這個情況下被調用。
    // 可以訪問組件實例 `this`
    console.log(this, 'beforeRouteUpdate'); //當前組件實例
    console.log(to, '組件獨享守衛beforeRouteUpdate第一個參數');
    console.log(from, '組件獨享守beforeRouteUpdate衛第二個參數');
    console.log(next, '組件獨享守beforeRouteUpdate衛第三個參數');
    next();
  },
  beforeRouteLeave(to, from, next) {
    // 導航離開該組件的對應路由時調用
    // 可以訪問組件實例 `this`
    console.log(this, 'beforeRouteLeave'); //當前組件實例
    console.log(to, '組件獨享守衛beforeRouteLeave第一個參數');
    console.log(from, '組件獨享守衛beforeRouteLeave第二個參數');
    console.log(next, '組件獨享守衛beforeRouteLeave第三個參數');
    next();
  }
}

</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>


</style>

helloWord組件代碼

<template>
  <div class="sider_box">
      <p @click="go">第一個頁面</p>
      <p @click="goTest">觸發讓它跳到test頁面檢查組件守衛功能</p>
  </div>
</template>
<script>
export default {
  data() {
    return {

    }
  },
  methods: {
    go(){
      this.$router.push({name:'navMenu'})
    },
    goTest(){
      this.$router.push({name:'test'})
    }
  }
}

</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

先從helloword跳到test可以看到控制台打印

再從test跳到helloword可以看到打印如下:

 

 

 

 以上就是完整的解釋了,看了那么多別人貼的代碼都是粘貼復制類型的實屬無奈,只好自己抽空寫一個幫助更多需要幫助的人;;;;(轉載需注明出處,謝謝合作!!!代碼這樣的還是自己花時間整理比較好)具體API參考vue官方文檔。。。

 內容原創,轉載請注明出處!!!!謝謝合作!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM