Vue Animations with v-for
Vue’s built-in <TransitionGroup> component facilitates the animation of components introduced to the page using v-for.
The < TransitionGroup > Component
When adding or removing items made using v-for, the <TransitionGroup> component is utilized to provide each element a unique animation.
Within the <TransitionGroup> component, tags generated with v-for need to be defined using the key attribute.
Only when we declare the <TransitionGroup> component as a specific tag using the tag prop—like in this example—will it be shown as an HTML tag.
{{ x }}
After being rendered by Vue, the code above produces this result:
- Apple
- Pizza
- Rice
Now that new items are being added to the list, we can add CSS code to make them animate:
In this case, adding new items to the ‘products’ array will automatically make them animated:Â
Example
App.vue:
The Component
New products are given animations using the component.
{{ x }}
Add and Remove Elements
When one element is removed from between another, the remaining elements will take its place. We will utilize the automatically produced v-move class to animate how the remaining list items fall into place when an element is deleted.
Let’s first examine an example where the removal of an element does not cause other objects to fall into place in an animated manner:
Example
App.vue:
The Component
New products are given animations using the component.
{{ x }}
The aforementioned example illustrates how, upon removal of an item, the items immediately follow it and leap into their new locations. When an item is deleted, we use the automatically produced v-move class to animate the remaining items.
The removed object still exists and occupies space until it is removed, thus the v-move class will not have any effect. Nevertheless, the other elements are animated when the removed item disappears. We can specify position: absolute; to the v-leave-active class so that it has something to animate for the v-move class. Position: absolute; sets the removed item to remain visible but not to take up space during the removal period.
All that separates this example from the previous one are the two additional CSS classes that are introduced on lines 14 and 17:
Example
App.vue:
A Larger Example
Let’s create a new example based on the previous one.
In this example, the animation of the entire list when a new item is added or removed, or when the entire array is sorted, is made even more evident.
In this illustration, we can:
- Click on the items to remove them.
- Arrange the things.
- Add new entries to the list at any random position.
Example
App.vue:
The Component
Items inside the component are animated when they are created or removed.
{{ x.dieNmbr }}