前面介绍 Vue.js 内置的过渡类名,Vue.js 还支持自定义类名,我们可以通过以下属性来自定义过渡类名:
enter-class
enter-active-class
enter-to-class (2.1.8+)
leave-class
leave-active-class
leave-to-class (2.1.8+)
注意,自定义过渡类名优先级高于普通的类名,这对于 Vue 的过渡系统和其他第三方 CSS 动画库(如 Animate.css)结合使用十分有用。例如:
(1)引入 Animate.css 动画库。
<!-- 动画库 --> <link href="https://cdn.jsdelivr.net/npm/animate.css@3.5.1" rel="stylesheet" type="text/css">
(2)使用 <transition> 元素的属性自定义类名,这些类名其实是 Animate.css 中定义的类名。
<transition name="custom-classes-transition" enter-active-class="animated tada" leave-active-class="animated bounceOutRight"> <p v-if="show">hello</p> </transition>
<html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vue</title> <!-- 使用 CDN 引入 Vue 库 --> <!-- <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> --> <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.7.9/vue.js"></script> <!-- 动画库 --> <link href="https://cdn.jsdelivr.net/npm/animate.css@3.5.1" rel="stylesheet" type="text/css"> </head> <body> <div id="app"> <button @click="show = !show">Toggle render</button> <transition name="custom-classes-transition" enter-active-class="animated tada" leave-active-class="animated bounceOutRight"> <p v-if="show">hello</p> </transition> </div> <script type="text/javascript"> var app = new Vue({ el: "#app", data: { show: true } }); </script> </body> </html>
运行效果如下图:
更多关于过渡相关的信息,请参考 Vue.js 官方文档:https://v2.cn.vuejs.org/v2/guide/transitions.html。