Vue 中監聽路由信息


一、監聽路由從哪來到哪去

watch:{
    $route(to,from){
      console.log(from.path);//從哪來
      console.log(to.path);//到哪去
    }
}

二、監聽路由變化獲取新老路由

watch:{
    $route:{
      handler(val,oldval){
        console.log(val);//新路由信息
        console.log(oldval);//老路由信息
      },
      // 深度觀察監聽
      deep: true
    }
  }

三、監聽路由變化觸發方法

1、

watch: {
    '$route'() {
        console.log('111')
    } 
}

2、

methods:{
  getPath(){
    console.log(1111)
  }
},
watch:{
  '$route':'getPath'
}

四、全局監聽路由

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/wechat-user-statistics',
      name: 'wechat-user-statistics',
      component: WechatUserStatistics
    },
    ....
  ]
})
// 全局監聽路由
router.beforeEach((to, from, next) => {
    console.log(to);
    next();
});

export default router

五、組件中監聽路由

 beforeRouteEnter (to, from, next) {
     // 在渲染該組件的對應路由被 confirm 前調用
     // 不!能!獲取組件實例 `this`
     // 因為當鈎子執行前,組件實例還沒被創建
 },
 beforeRouteUpdate (to, from, next) {
     // 在當前路由改變,但是該組件被復用時調用
     // 舉例來說,對於一個帶有動態參數的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉的時候,
     // 由於會渲染同樣的 Foo 組件,因此組件實例會被復用。而這個鈎子就會在這個情況下被調用。
     // 可以訪問組件實例 `this`
 },
 beforeRouteLeave (to, from, next) {
     // 導航離開該組件的對應路由時調用
     // 可以訪問組件實例 `this`
 }

轉載於:https://blog.csdn.net/Umbrella_Um/article/details/107512056

 


免責聲明!

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



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