#development #frontend #javascript #vuejs

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.

2    <User :user="user" :key="user.id" />

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:

2    <transition>
3        <span :key="text">{{ text }}</span>
4    </transition>

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.