Adding Transition Effects
With Vue.js’ transition hooks you can apply automatic transition effects when elements are inserted into or removed from the DOM. There are three options to implement transitions with Vue.js: CSS transitions, CSS animations, and JavaScript functions.
All Vue.js transitions are triggered only if the DOM manipulation was applied by Vue.js, either through built-in directives, e.g. v-if, or through ViewModel instance methods, e.g. vm.$appendTo().
CSS Transitions
To enable CSS transitions on an element, simply give it an empty v-transition directive:
1 | <p class="msg" v-if="show" v-transition>Hello!</p> |
You will also need to provide CSS rules for v-enter and v-leave classes (the class names can be configured with Vue.config()):
1 | .msg { |
Hello!
Now when the show property changes, Vue.js will insert or remove the <p> element accordingly, and apply transition classes as specified below:
When
showbecomes false, Vue.js will:- Apply
v-leaveclass to the element to trigger the transition; - Wait for the transition to finish; (listening to a
transitionendevent) - Remove the element from the DOM and remove
v-leaveclass.
- Apply
When
showbecomes true, Vue.js will:- Apply
v-enterclass to the element; - Insert it into the DOM;
- Force a CSS layout so
v-enteris actually applied; - Remove the
v-enterclass to trigger a transition back to the element’s original state.
- Apply
It is important to ensure that the target element’s CSS transition rules are properly set and it will fire a transitionend event. Otherwise Vue.js will not be able to determine when the transition is finished.
CSS Animations
CSS animations are applied in a similar fashion with transitions, but using the v-animation directive. The difference is that v-enter is not removed immediately after the element is inserted, but on an animationend callback.
Example: (omitting prefixed CSS rules here)
1 | <p class="animated" v-if="show" v-animation>Look at me!</p> |
1 | .animated { |
JavaScript Functions
Vue.js provides a way to call arbitrary JavaScript functions during element insertion/removal. To do that you first need to register your effect functions:
1 | Vue.effect('my-effect', { |
The third argument, timeout, is a wrapped version of setTimeout. You should use it in place of setTimeout so that when an effect is cancelled, its associated timers can be cleared.
Then you can use it by providing the effect id to v-effect:
1 | <p v-effect="my-effect"></p> |
Next: Composing ViewModels.