Update component when we change route in Vue

In this article, we will learn how to update/re-render a Vue component on route change.

In Vue, when we create a SPA app using Vue Router, it is common to create a path parameter that helps to navigate through different components in the app.

However, sometimes when we use <router-link> to try to change the route in the address bar to fetch data from an API, it does not render the updated information on the component of the page.

This is because the mounted() or created() hook does not get fired.

Let’s see an example to solve this issue.

Let’s say we have a page where we fetch data of a person depending on the slug-id of the route in the address bar.

<template>
    <div>
        <ul style="display:flex; justify-content:space-around">
            <li>
                <router-link to="/person/2">person 2 </router-link>
            </li>
            <li>
                <router-link to="/person/3">person 3 </router-link>
            </li>
            <li>
                <router-link to="/person/4">person 4 </router-link>
            </li>
        </ul>

        <div v-if="personData">
            <h2>
                {{ personData.data.first_name }}
            </h2>
            <img :src="personData.data.avatar" alt="">
            <div>
                Person ID = {{ personData.data.id }}
            </div>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            personData: null
        }
    },
    async created() {
        const personId = this.$route.params.id
        const response = await fetch(`https://reqres.in/api/users/${personId}`)
        this.personData = await response.json()
    }
}
</script>

We have a Person component where we fetch data from the API in the created() hook and display it on the template.

update component on route change

Now, as you can see when we try to navigate to person 3 and person 4 using router-link, the component does not get updated with the clicked person’s information.

The reason for this is that the created() hook is only fired once when we first visited the page or when we reload the page manually.

And when we used <router-link> to get the information of the other person, the created() hook was not fired.

To solve this, we have to somehow tell the vue-router to update the component or re-render the page when we change the route in our Vue application.

So how can we update the Vue component on route change?

Well, the most easy fix to this is to add :key=”$route.fullPath” to < router-view > in App.vue file.

<template>
  <div id="app">
    <router-view :key="$route.fullPath"/>
  </div>
</template>

This set the entire <router-view> to re-render whenever its path changes in the application.

Since you have added the key in your <router-view> so every path in that router will update whenever there is a path change.

update vue component on route change
Scroll to Top