Vue封装的过度与动画(transition-group、animate.css)
目录
- 1. Vue封装的过度与动画
- 1.1 动画效果1
- 1.2 动态效果2
- 1.3 使用第三方动画库animate.css
1. Vue封装的过度与动画
作用:在插入、更新或移除DOM元素时,在合适的时候给元素添加样式类名
1.1 动画效果1
Test1.vue:
- transition内部只能包含一个子标签。包裹要过渡的元素。基本原理是Vue会在合适的时候自动给子标签添加不同的class样式属性
- 使用了name属性就可以分别控制多个动画了
- appear属性第一次显示的时候就有动画效果。相当于
:appear="true"
<template><div><button @click="isShow = !isShow">显示/隐藏</button><transition name="trans1" appear><h1 v-show="isShow">你好啊</h1></transition></div>
</template><script>export default {name:'Test1',data() {return {isShow:true}}}
</script><style scoped>h1{background-color: orange;}<!-- 元素进入过程中 -->.trans1-enter-active{animation: myFlash 0.5s linear;}<!-- 元素离开过程中 -->.trans1-leave-active{animation: myFlash 0.5s linear reverse;}<!-- 准备的动画 -->@keyframes myFlash {from{transform: translateX(-100%);}to{transform: translateX(0px);}}
</style>
动画效果静态时如下:
1.2 动态效果2
Test2.vue:
- 有多个元素需要过度,可以使用
<transition-group>
,且每个元素都要指定key值
<template><div><button @click="isShow = !isShow">显示/隐藏</button><transition-group name="trans1" appear><h1 v-show="!isShow" key="1">你好啊</h1><h1 v-show="isShow" key="2">jack</h1></transition-group></div>
</template><script>export default {name:'Test2',data() {return {isShow:true}}}
</script><style scoped>h1{background-color: orange;}/* 进入的起点、离开的终点 */.trans1-enter,.trans1-leave-to{transform: translateX(-100%);}/* 进入的终点、离开的起点 */.trans1-enter-to,.trans1-leave{transform: translateX(0);}.trans1-enter-active,.trans1-leave-active{transition: 0.5s linear;}
</style>
动画效果静态时如下:
1.3 使用第三方动画库animate.css
使用cnpm install animate.css
安装第三方动画库。想要更多可以去https://www.npmjs.com/进行搜索。还要另外两种方式引入animate.css文件
- 直接下载animate.css文件,放到src/assets/css路径下,然后通过
import ./assets/css/animate.css
进行引入 - 直接下载animate.css文件,放到public/css路径下,然后在index.html页面中通过
<style rel="stylesheet" href="<%= BASE_URL %>css/animate.css"></style>
进行引入
Test3.vue:直接在transition-group指定属性就可以了。指定的属性可以去https://animate.style/官网去查看
<template><div><button @click="isShow = !isShow">显示/隐藏</button><transition-group appearname="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">jack</h1></transition-group></div>
</template><script>import 'animate.css'export default {name:'Test3',data() {return {isShow:true}}}
</script><style scoped>h1{background-color: orange;}</style>
动画效果静态时如下: