#development #javascript

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.

1<template>
2    <User :user="user" :key="user.id" />
3</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:

1<template>
2    <transition>
3        <span :key="text">{{ text }}</span>
4    </transition>
5</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.