Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

gabrielbuzzi's avatar

[Vue 2] Reload component when same route is requested

The Scenario

My application in a SPA, and i'm building using Vue 2 and Vue Router 2.

I have a page that show some data about the user, the route is like "/user/:id/details", this route load a components that have a hook mounted that load via "ajax" request the data about the user.

And i have in my sidebar a kind of search, where i write the name of the user and i can click to access the page.

The problem

When i already load the component one time, for example: "accessed the route /user/1/details". If i click in the router-link to go to "/user/2/details" the component don't hook the mounted hook again, since the component is not destroyed and the data is not reloaded, so the url change, but the data don't.

What i need

When i click in the router-link, the component of the current page need to be destroyed and created/mounted again.

Some code

Details.vue mounted hook

mounted () {
    const vm = this

    vm.$http.get('/api/users/' + vm.$route.params.id)
        .then(response => {
            vm.user = response.data
        })
}

My route

{ path: '/user/:id/details', component: Details, name: 'user.details' },

Image of the situation

Image of Problem

In this image i first access the detail of John doe, then i tried to click in Jane doe, but in this case the component is not destroyed and created again, so the hook mounted never is throwed when i try to access a page that use the same component of the current page.

0 likes
11 replies
jurjen's avatar

You can watch for changes in the route id parameter.

mounted () {
    this.getUser(this.$route.params.id);
},
methods: {
    getUser(id) {
        const vm = this

        vm.$http.get('/api/users/' + id)
             .then(response => {
                    vm.user = response.data
        })
    }
},
watch: {
    '$route.params.id'(newId, oldId) {
        this.getUser(newId)
    }
}
4 likes
gabrielbuzzi's avatar

Works, but i still think that sounds like a "jerry-rig", "quick fix"

gabrielbuzzi's avatar

@jurjen Hmm, nice, so it`s ok since the docs say that this is the approach to solve this problem. thanks

matthagemann's avatar
Level 1

The simplest solution is to add a :key attribute to <router-view>:

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

This is because Vue Router does not notice any change if the same component is being addressed. With the key, any change to the path will trigger a reload of the component with the new data.

16 likes
benji's avatar

Is there any more info on how this works.? I tried it and it works perfectly.

Please or to participate in this conversation.