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

同樣的和前面路由鉤子相似的步驟vue

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

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組件代碼this

<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能夠看到控制檯打印spa

再從test跳到helloword能夠看到打印以下:code

 

 

相關文章
相關標籤/搜索