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
2
3
4
5
6
7
8
9
10
11
12
.msg {
transition: all .3s ease;
height: 30px;
padding: 10px;
background-color: #eee;
overflow: hidden;
}

.msg.v-enter, .msg.v-leave {
height: 0;
padding: 0 10px;
opacity: 0;
}

Hello!

Now when the show property changes, Vue.js will insert or remove the <p> element accordingly, and apply transition classes as specified below:

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
.animated {
display: inline-block;
}


.animated.v-enter {
animation: fadein .5s;
}


.animated.v-leave {
animation: fadeout .5s;
}


@keyframes fadein {
0% {
transform: scale(0);
}

50% {
transform: scale(1.5);
}

100% {
transform: scale(1);
}

}

@keyframes fadeout {
0% {
transform: scale(1);
}

50% {
transform: scale(1.5);
}

100% {
transform: scale(0);
}

}
Look at me!

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
2
3
4
5
6
7
8
Vue.effect('my-effect', {
enter: function (el, insert, timeout) {
// insert() will actually insert the element
},
leave: function (el, remove, timeout) {
// remove() will actually remove the element
}
})

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.