Vue Transition 过渡组件 + animate.style 动画库的使用
Vue 提供了 transition
的封装组件,可以给被包裹的任何元素和组件添加进入/离开过渡效果。详情:Vue-进入/离开 & 列表过渡
本文主要记录 Vue Transition 组件搭配 animate.style 动画库的使用步骤:
animate.style 官网:animate.style 动画库
安装 animate 动画库
打开 animate.style 的官网首页就有该动画库的安装使用步骤详解,这里就简单记录一下,比如使用 npm 安装
npm install animate.css -S
安装完成后可以在项目的 package.json 文件中搜索查看下是否有 animate.css 文件且对应着安装的版本号。
导入和使用 animate 动画库
然后在需要使用该动画库的页面的 script 中导入 animate.style 的样式文件:
// 导入动画样式库
import 'animate.css'
然后在页面中将在 animate.style 动画库中相中的动画效果的 class 类名添加给对应的页面元素即可。注意:如果安装的 animate.css 的版本 >V3.0 还需要给动画样式一并添加上 animate__animated
的前缀,这样动画才会生效!
使用示例
演示 Vue 的 transition 过渡组件搭配 animate.style 的使用(前提:安装和导入步骤已完成)
<!-- 演示动画的使用 -->
<button @click="flag = !flag">显示/隐藏</button>
<Transition leave-active-class="animate__animated animate__fadeOut"
enter-active-class="animate__animated animate__flash">
<div class="box" v-if="flag"></div>
</Transition>
主要就是将需要使用动画的元素/组件 包裹到 vue 提供的 transition 组件中,然后给 transition 组件添加 leave-active-class 隐藏的样式类名 和 enter-active-class 显示的样式类名即可。
注:Transition 组件是用来过渡单块元素的(即:为元素整体添加过渡效果的情况),而如果我们要过渡的元素是一个列表(内部使用了 v-for 进行循环的情况)那我们需要使用 TransitionGroup 组件。
TransitionGroup 过渡列表
示例如下:Vue3 + TS 的写法
HTML:
<!-- 演示过渡列表 -->
<button @click="add">add</button>
<button @click="pop" style="margin-left: 20px;">pop</button>
<div class="numberlist">
<TransitionGroup enter-active-class="animate__animated animate__bounceIn"
leave-active-class="animate__animated animate__fadeOutDown">
<div v-for="item in numberList" :key="item" class="numberitem">{{ item }}</div>
</TransitionGroup>
</div>
typeScript:
// 导入动画样式库
import 'animate.css'
import { reactive } from "vue";
const numberList = reactive<number[]>([1, 2, 3, 4, 5, 6])
const add = () => {
numberList.push((numberList.length + 1))
}
const pop = () => {
numberList.pop()
}
CSS:(less)
.numberlist {
width: 100%;
display: flex;
flex-wrap: wrap;
font-size: 40px;
.numberitem {
margin: 10px;
}
}
静态效果:
TransitionGroup 过渡列表效果描述:添加的动画效果是作用于每一个列表项的,所以在往列表中添加元素或者移除元素时单项是有动画效果的(比如:淡入淡出),实际效果可以自己复制代码运行体验一下哦~感觉很不错的!