一、基本使用
1. 使用<transition></transition>标签包裹要加动画的元素
2. 标签中添加属性name,表示执行动画的名字,不加默认为v
3.标签中添加属性appear,值为布尔值true/false,表示是否在初始化时就执行动画
解析后在动画执行期间会给元素添加以下类名
name值-enter(进入的起点),name值-enter-to(进入的终点),name值-enter-active(进入过程中),
name值-leave(离开的起点),name值-leave-to(离开的终点),name值-leave-active(离开过程中)
通过使用不同的类型添加css样式实现过度
1. animation和name值-enter-active/name值-leave-active组合
<template>
<div>
<button @click="isShow = !isShow">显示/隐藏</button>
<transition name="hello" appear>
<h1 v-show="isShow">你好啊!</h1>
</transition>
</div>
</template>
<script>
export default {
name: 'Test',
data() {
return {
isShow: false
}
},
}
</script>
<style scoped>
.hello-enter-active{
animation: showHide 1s;
}
.hello-leave-active{
animation: showHide 1s reverse;
}
@keyframes showHide{
from{
transform: translateX(-100%)
},
to{
transform: translateX(0px)
}
}
</style>
2. 所有添加样式组合
<template>
<div>
<button @click="isShow = !isShow">显示/隐藏</button>
<transition name="hello" appear>
<h1 v-show="isShow">你好啊!</h1>
</transition>
</div>
</template>
<script>
export default {
name: 'Test',
data() {
return {
isShow: false
}
},
}
</script>
<style scoped>
.hello-enter-active, .hello-leave-active{
transition: 1s liner;
}
.hello-enter, .hello-leave-to{
transform: translateX(-100%)
}
.hello-enter-to, .hello-leave{
transform: translateX(0px)
}
</style>
二、注意事项
1. transition标签中只能有一个根标签
<template>
<div>
<button @click="isShow = !isShow">显示/隐藏</button>
<transition name="hello" appear>
<div v-show="isShow">
<h1 key="1">你好啊!</h1>
<h1 key="2">吃了吗?</h1>
</div>
</transition>
</div>
</template>
2. 多个根标签的时候用<transition-group>标签包裹,并且每个子标签要有唯一key值
<template>
<div>
<button @click="isShow = !isShow">显示/隐藏</button>
<transition-group name="hello" appear>
<h1 v-show="!isShow">你好啊!</h1>
<h1 v-show="isShow">吃了吗?</h1>
</transition>
</div>
</template>
三、集成第三方动画 animate.css
主页地址:Animate.css | A cross-browser library of CSS animations.
安装
npm install animate.css --save
引入
import 'animate.css'
使用:
<transition
appear
name=“animate__animated animate__bounce”
enter-active-class="进入的动画"
leave-active-class="离开的动画"
>
进入的动画/离开的动画在官网上找
若有需要改进的地方,欢迎小伙伴评论~