A Transition means changing from one state to another. If some CSS property(width, height, etc) is changed suddenly it will be like a flash. So, to make this sudden change a bit smoother, we have a CSS property named transition. which will make any CSS property change smoothly over a period of time.
Let me give you a small example...
So, this is a basic CSS transition with transition-duration: 2s. Like this, we have three properties for CSS transition. Those are transition-property, transition-duration and transition-delay
Let’s now go into what Vue will provide on top of basic CSS transitions. So, Vue is adding this magic to elements that are getting inserted, updated, and removed from DOM. This basically will happen for v-if, v-show, and any dynamic component.
Vue Transitions are providing a tag “<transition>”. Our element which is rendered based on v-if can be wrapped inside this transition tag. This transition tag will have a name.
Now, will go into how we can apply a transition for the written code. Vue will provide us 6 phases while an element enter/leave the DOM.
1. enter: This is the first / start phase of the element. which is added before the element is inserted.
2. enter-active: This is where actual transition is applied. On which property, and for how many seconds. This is removed when tranistion ends.
3. enter-to: This is the last phase of enter.At the same time, enter is removed.
- At first, when the paragraph is entering the DOM, it will have opacity: 0
- And, when opacity:1 will be rendered slowly within 5s
- At the same time as enter-active, enter-to comes up from the top as it is Y-axis. (here enter class will be removed)
Next, will see the classes provided for the element when it is leaving the DOM.
leave: This is the first phase of leave when an element is removed from DOM.
leave-active: This is the active phase of leave, where we can apply the actual transition with property and duration.
leave-to: This is the last phase before the element is removed, at the same time leave class is removed.
- First we have moved paragraph to a bit top on Y axis.
- Next, applied a transition on opacity with 5s duration
- And then, while the last phase of leave.. opacity is zero. it will disappear.
In the above example, I have only used transition. but we can also use animations. using the same enter, leave classes. we will move one more step ahead and will see what else we can do with this enter and leave.
Like, we have life cycle hooks.. beforeCreate, created, beforeMount, mounted, etc. we also have hooks here, where we can write our required functionality.
There is much more that vue is providing through transitions. like, applying transitions on the list (List Transitions), and also we can give custom classes for the transitions.