Vue: Force reload of Vue component with dynamic route parameters

Last modified Jan 13 2021 12:04 by Kees de Kooter

The issue

When you define a route with parameters - say /product/:id - the view component is only rendered once. From vue-router's point of view nothing needs to change if you navigate to a different :id. mounted() and beforeRouteUpdate hooks in the component will not be triggered.

This is explained in the documentation. The first proposed solution - the watch - implies mingling router logic into your component. Not very desirable. And the second proposed solution does not work.

An hint of an alternative solution is tucked away in a comment in a code sample in the vue-router documentation:

// For example, for a route with dynamic params `/foo/:id`, when we
// navigate between `/foo/1` and `/foo/2`, the same `Foo` component instance
// will be reused (unless you provided a `key` to `<router-view>`)

Unfortunately this key property is not documented anywhere else.

The solution

Turns out that the proper syntax is this:

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

Now the component is rendered on every route parameter change, and all hooks are being triggered. And the component itself is not polluted with router logic.