Routing the same component, the component doesn't reload in Vue with Vue Router?

- Andrés Cruz

En español
Routing the same component, the component doesn't reload in Vue with Vue Router?

Many times when we use Vue Router, we need to call the same component to reload its information; but in Vue, although the URL varies, we will see that the content does not change, this is the behavior that Vue Router has by default but we can force it to update; For that, I bring you a couple of ways:

Not reloading the component, is the expected behavior in Vue, which is trying to be optimal and reuse existing components.

Key in router-view

A somewhat drastic solution is to place a key in our router-view, this will (which is a normal behavior in Vue components) reload this container (the SPA web) as soon as the URL path changes; for that:

<router-view :key="$route.path"></router-view>

beforeRouteUpdate in components

Another solution, which is the one I like the most, since it allows us to define this behavior in the components we need, and have more control over what we want to reload and NOT the entire page, is to use the event:

data() {
    return {
      sectionIndex: this.$route.params.s
      classIndex: this.$route.params.c 
    };
  },
  beforeRouteUpdate(to) {
    this.sectionIndex = to.params.s;
    this.classIndex = to.params.c;
  },

In which, we force the update of our parameters by accessing them, note that with the to parameter, in beforeRouteUpdate, we can obtain exactly the same parameters with which the route of this component works.

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.