Home

May 16, 2018, 2 min read

Here is some Key Advice for Vue

When using Vue.js, it's good to know that the key attribute is useful not only because Vue keeps yelling at you when you forget to add in in a v-for loop.

It can also be used to force replacement of a component based on some state or change that Vue could not have detected by itself. This is useful to force rerendering and thus consistency with the underlying data in specific situations or to trigger transitions. The docs explain this pretty well: https://vuejs.org/v2/api/#key

One use case that I really did not have on my radar is for what I would call "sibling pages" or views when using something like vue-router.

The following is a shameless ripoff from Chris Fritz Vue tips and tricks video: https://www.youtube.com/watch?v=7lpemgMhi0k&feature=youtu.be&t=17m36s - so all kudos to him.

Let's say you have a page/component that is triggered by multiple URLs, e.g. /products/1 and /products/2 etc. - with the simple router-view below, even when updating the component state internally by fetching a new product dataset, the component may not update properly because the route change did not trigger a component rerendering.

<router-view />

This would be most apparent when having "previous" and "next" buttons on your product page to go from one sibling to the next. It can very easily be fixed by telling Vue to key the currently routed component with the full path:

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

This will make sure that a URL change will mark the component as having changed, forcing a rerender, ensuring we see exactly the current state.

There is a small performance hit in forcing a rerender on every navigation, but well worth not having to worry about seeing mixed up page content.

keep_breathing