
VueJS keys to force updates
15 Jun 2022 #javascript #vue
In @vuejs you can give components (not just list elements) a key, too. This forces the element to be replaced if the key changes.
This can for example be useful when you are using lifecycle methods (e.g. onMounted
) or when you want to trigger transitions again.
<template> <User :user="user" :key="user.id" /></template>
The documentation learns you that ut can also be used to force replacement of an element/component instead of reusing it. This can be useful when you want to:
- Properly trigger lifecycle hooks of a component
- Trigger transitions
For example:
<template> <transition> <span :key="text">{{ text }}</span> </transition></template>
When text changes, the <span>
will always be replaced instead of patched, so a transition will be triggered.
Tip found here.
PS: you can learn about the <transition>
element here.