watch監聽路由變化詳解


一、watch監聽路由的方法

通過watch監聽,當路由發生變化的時候執行。

方法一:

watch:{
  $router(to,from){
       console.log(to.path)
  }
}

方法二:

watch: {
   $route: {
     handler:  function (val, oldVal){
       console.log(val);
     },
     // 深度觀察監聽
     deep:  true
   }
},

方法三:

watch: {
   '$route' : 'getPath'
},
methods: {
   getPath(){
     console.log( this .$route.path);
   }
}

二、key-用來阻止“復用”的

Vue 為你提供了一種方式來聲明“這兩個元素是完全獨立的——不要復用它們”。只需添加一個具有唯一值的 key 屬性即可(Vue文檔原話)

<router-view :key= "key" ></router-view>
 
computed: {
   key() {
     return  this .$route.name !== undefined?  this .$route.name + new  Date():  this .$route + new  Date()
   }
}

使用computed屬性和Date()可以保證每一次的key都是不同的,這樣就可以如願刷新數據了。

三、全局監聽路由(通過vue-router的鈎子函數beforeRouteEnter/beforeRouteUpdate/beforeRouteLeave)

一般會在router里面加跳轉驗證才會用到這個方法

方法一:

watch:{
       $route(to,from){
         if (to.path ==  '/'  || to.path ==  '/Prisoner'  || to.path ==  '/Goods'  || to.path ==  '/Time'  || to.path ==  '/Mine' ){
           /**
            * $store來自Store對象
            * dispatch 向 actions 發起請求
            */
           this .$store.dispatch( 'showTabBar' );
         } else {
           this .$store.dispatch( 'hideTabBar' );
         }
       }
     },
     beforeRouteEnter (to, from, next) {
       // 在渲染該組件的對應路由被 confirm 前調用
       // 不!能!獲取組件實例 `this`
       // 因為當鈎子執行前,組件實例還沒被創建
     },
     beforeRouteUpdate (to, from, next) {
       // 在當前路由改變,但是該組件被復用時調用
       // 舉例來說,對於一個帶有動態參數的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉的時候,
       // 由於會渲染同樣的 Foo 組件,因此組件實例會被復用。而這個鈎子就會在這個情況下被調用。
       // 可以訪問組件實例 `this`
     },
     beforeRouteLeave (to, from, next) {
       // 導航離開該組件的對應路由時調用
       // 可以訪問組件實例 `this`
     },

 

方法二:

在app.vue的create中加入下面代碼,然后進行判斷

this.$router.beforeEach((to ,from,next) =>{
       console.log(to);
       next(); 
})

 


免責聲明!

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



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