How vue monitors routing changes

Summary of several ways to monitor route changes


1. Where does the monitoring route come from?

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

2. Monitor routing changes to obtain new and old routing information

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

3. Monitoring route change trigger method

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

4. Global monitoring route

Add the following code in the create of app.vue, and then make a judgment

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

How to listen for changes in routing parameters in components?

When using route parameters, such as navigating from /user/foo to /user/bar, the original component instance will be reused.

Because both routes render the same component, reuse is more efficient than destroying and recreating. However, this also means that the component's lifecycle hooks will no longer be called.

Then if we want to monitor the change of routing parameters in the component, we can only use the watch (monitoring changes) $route object, or use the guard in the component of beforeRouteUpdate.

1. Monitor $route

const User = {
    
    
  template: '...',
  watch: {
    
    
    $route(to, from) {
    
    
      // 对路由变化作出响应...
    }
  }
}

2. Through the navigation guard in the component

beforeRouteUpdate , (same level as created(){} lifecycle function)

const User = {
    
    
  template: '...',
  beforeRouteUpdate(to, from, next) {
    
    
    // react to route changes...
    // don't forget to call next()
  }
}

Guess you like

Origin blog.csdn.net/qq_45585640/article/details/128959854