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:

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: – 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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s