Vue动画:transition组件

Vue动画:transition组件

Vue中新增的动画语法,一般用于实现转场动画

基本使用

Vue 提供了 transition 的封装组件,在v-ifv-show中,可以给任何元素和组件添加进入/离开过渡(会在动画过程中依次给组件中的元素切换6个类名)

1
2
3
4
5
6
7
8
9
10
<div id="demo">
<button v-on:click="show = !show">
Toggle
</button>

<transition>
<p v-show="show">hello</p>
</transition>

</div>
1
2
3
4
5
6
new Vue({
el: '#demo',
data: {
show: true
}
})

六个类名的处理

1
2
3
4
5
6
7
8
9
10
11
12
.v-enter-active,
.v-leave-active {
transition: opacity 0.5s;
}
.v-enter,
.v-leave-to {
opacity: 0;
}
.v-leave,
.v-enter-to {
opacity: 1;
}

自定义类名前缀

如果有多个动画,可以指定name属性

1
2
3
<transition name="fade">
<p v-show="show">hello</p>
</transition>
  • 样式
1
2
3
4
5
6
7
8
9
10
11
12
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter,
.fade-leave-to {
opacity: 0;
}
.fade-leave,
.fade-enter-to {
opacity: 1;
}

结合动画使用

结构

1
2
3
4
5
6
7
8
9
<!-- 实现一个h1标签的入场和离场的动画 -->
<div id="app">
<button @click="show = !show">切换</button>

<transition name="fade">
<h1 v-show="show">{{ msg }}</h1>
</transition>

</div>

样式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* @keyframs自带开始和结束,所以不用设置v-enter、v-enter-to等 */
.fade-enter-active {
animation: bounce-in 0.5s;
}
.fade-leave-active {
animation: bounce-in 0.5s reverse;
}
@keyframes bounce-in {
0% {
transform: scale(0);
}
50% {
transform: scale(1.5);
}
100% {
transform: scale(1);
}
}

自定义过渡的类名

通过给以下attribute赋值,可以自定义过渡类名:

  • enter-class
  • enter-active-class
  • enter-to-class
  • leave-class
  • leave-active-class
  • leave-to-class
1
2
3
<transition enter-active-class="in" leave-active-class="out">
<h1 v-show="show">{{ msg }}</h1>
</transition>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
.in {
animation: bounce-in 0.5s;
}
.out {
animation: bounce-in 0.5s reverse;
}
@keyframes bounce-in {
0% {
transform: scale(0);
}
50% {
transform: scale(1.5);
}
100% {
transform: scale(1);
}
}

配合animate.css使用

通常不自己写动画,而是采用其他人写好的动画,例如animate.css

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<link href="https://cdn.jsdelivr.net/npm/animate.css@3.5.1" rel="stylesheet" type="text/css">

<div id="example-3">
<button @click="show = !show">
Toggle render
</button>

<!-- animated 是基础类名,必须写 -->
<transition
enter-active-class="animated tada"
leave-active-class="animated bounceOutRight"
>
<p v-if="show">hello</p>
</transition>

</div>