Transition when replacing elements with Vue.js

Transition when replacing elements of different types

The transition that occurs when replacing two elements of different types is very simple, it is enough to wrap both elements with a transition element.

Example

See the Pen Basic transition between elements by Web programming (@chos) on CodePen.


Transition Modes

vue

During the transition in the previous example, the property change on both elements occurs simultaneously. As a result, both elements are visible during the animation (which is not the most beautiful). The new element that has yet to be rendered is always positioned below the disappearing element. It is unnatural that this element comes to the right place only when the first element completely disappears ie. when the animation is finished (and then the jump of the element is noticed).
In order to avoid this ugly behavior, it is necessary that the element that disappears completely finishes the animation, before the animation of the element that appears begins. Vue.js achieves this by defining the so-called mode of transition.
There are two possibilities for the value of the “mode” attribute:

  • out-in – the currently visible element performs the animation first, and only after that animation is finished does the animation of the new element begin. This mod is used in most cases!
  • in-out – First, the animation is performed by the new element, and only after that animation is finished, the animation of the existing element starts.

Therefore, it is sufficient to define the value of the mode attribute with one of the two offered values.

Example

In this example, the attribute mode="out-in"

is added to the transiton element

See the Pen Mod transition elements by Web programming (@chos) on CodePen.

Transition when replacing elements of the same type

If two elements of different types (e.g. “p” and “div”) are being replaced, the transition will be performed, but if elements of the same type are being replaced, you need to add a “key” attribute with different values for each element in order for Vue.js to distinguish them!

For this reason, we can remove the v-if and make a transition between the two states of the “key” attribute:

Transition between components

The transition between components is even simpler than the simple transition between the same elements because it does not require the “key” attribute:

HTML

JavaScript