这是我参与【第四届青训营】笔记创作活动的第6天。
1、vue动画的理解
操作 css 的 trasition(过渡)或 animation(动画)
Vue会给目标元素添加 / 移除特定的 class
2、基本过渡动画的编码
- 在目标元素外包裹
- 定义class样式
(1)指定过渡样式: transition
(2)指定隐藏时的样式: opacity / 其它
3、过渡的类名
xxx-enter-active: 指定显示的transition
xxx-leave-active: 指定隐藏的transition
xxx-enter: 指定隐藏时的样式
标签使用:
<template>
<ul>
<transition-group name="todo" appear>
<!-- 向子组件传输li的数据 -->
<TodoItem v-for="item in todolists" :key="item.id" :value="item" />
</transition-group>
</ul>
</template>
以下三种方式都可以实现效果:
(1)过渡代码示例:
<style scoped>
h1 {
background-color: orange;
} /*进入的起点、离开的终点*/
.todo-enter,.todo-leave-to{
transform: translatex(-100%);
}
.todo-enter-active,.todo-leave-active{
transition: 0.5s linear;
} /*进入的终点、离开的起点*/
.todo-enter-to,.todo-leave{
transform: translatex(0);
}
</style>
(2)动画代码示例:
<style scoped>
ul {
overflow: hidden;
margin-top: 12px;
border: 1px solid gray;
border-bottom: none;
border-radius: 3px;
}
.todo-enter-active {
animation: todoAni 0.5s linear;
}
.todo-leave-active {
animation: todoAni 0.5s linear reverse;
}
@keyframes todoAni {
from {
transform: translateX(100%);
}
to {
transform: translateX(0px);
}
}
</style>
(3)使用第三方动画库
<template>
<div>
<button @click="isShow = !isShow">显示/隐藏</button>
<transition-group appear name="animate__animated animate__bounce" enter-active-class="animate__swing" leave-active-class="animate__backOutUp" >
<h1 v-show="!isShow" key="1">你好啊!</h1>
<h1 v-show="isShow" key="2">尚硅谷!</h1>
</transition-group>
</div>
</template>
<script>
import 'animate.css' export default {
name:'Test',
data() {
return { isShow:true }
},
}
</script>
<style scoped>
h1{ background-color: orange; }
</style>
4、总结
作用:在插入、更新或移除 DOM 元素时,在合适的时候给元素添加样式类名。
写法:
- 准备好样式:
元素进入的样式:
- v-enter:进入的起点
- v-enter-active:进入过程中
- v-enter-to:进入的终点
元素离开的样式:
- v-leave:离开的起点
- v-leave-active:离开过程中
- v-leave-to:离开的终点
- 使用
<transition>包裹要过度的元素,并配置 name 属性:
<transition name="hello">
<h1 v-show="isShow">你好啊!</h1>
</transition>
备注:
- 若有多个元素需要过渡,则需要使用
<transition-group>:,且每个元素都要指定 key 值。 - appear = true 简写为 appear,表示初始化就触发动画
- transition 省略 name 属性,默认动画 css 的 class 名为 v-enter-active
- 配置了 name 就是 name-enter-active
- transition 标签在模板解析完成之后会被消掉