Vue封装的过度与动画
-
作用:在插入、更新或移除 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值
-
可以使用第三方动画库来实现动画效果
-
代码演示
<template>
<div>
<button @click="isShow = !isShow">点击显示</button>
<transition appear>
<h1 v-show="isShow">这是一个H1</h1>
</transition>
<!-- 多个元素过度 -->
<transition-group appear name="weather">
<p key="1" v-show="isShow" style="background-color: pink;">今天是晴天</p>
<p key="2" v-show="!isShow" style="background-color: blue;">今天是阴天</p>
</transition-group>
<!-- 使用动画库 -->
<transition
appear
name="animate__animated animate__bounce"
enter-active-class="animate__wobble"
leave-active-class="animate__backOutDown"
>
<div class="fruits" key="1" v-show="isShow">苹果</div>
</transition>
<transition
appear
name="animate__animated animate__bounce"
enter-active-class="animate__fadeInLeft"
leave-active-class="animate__fadeOutRight"
>
<div class="fruits" key="1" v-show="isShow">香蕉</div>
</transition>
</div>
</template>
<script>
// 引入css动画库
import 'animate.css'
export default {
name: "Son",
data() {
return {
isShow: true,
};
},
};
</script>
<style scoped>
h1 {
background-color: red;
}
.fruits {
margin-left: 10px;
background-color: aquamarine;
}
/* 手动设置动画 */
/* .v-enter-active{
animation: move 1s;
}
.v-leave-active {
animation: move 1s reverse;
}
@keyframes move {
from{
transform: translateX(-100%);
}
to{
transform: translateX(0%);
}
} */
/* 使用Vue提供的<transition>标签自动添加动画 需要使用vue提供的类名 */
.v-enter,
.v-leave-to {
transform: translateX(-100%);
}
.v-enter-active,
.v-leave-active {
transition: 1s;
}
.v-enter-to,
.v-leave {
transform: translateX(0%);
}
/* 多个元素过渡 */
.weather-enter,
.weather-leave-to {
transform: translateX(-100%);
}
.weather-enter-active,
.weather-leave-active {
transition: 1s;
}
.weather-enter-to,
.weather-leave {
transform: translateX(0%);
}
</style>