1,使用组件的方式封装动画,
2,使用动画钩子设置样式
3,在组件中设置插槽,方便父元素自定义标签
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="./js/vue.js"></script> <script src="./js/velocity.min.js"></script> </head> <body> <div class="app"> <child :show='show'> <h3>动画封装</h3> </child> <child :show='show'> <h5>采用组件的方式</h5> </child> <button @click='btnClick'>toggle</button> </div> <script> // 封装动画以组件的方式 Vue.component('child', { props: ["show"], // 样式以动画钩子的形式展示 template: `<transition @before-enter='beforeEnter' @enter='enter' @before-leave='beforeLeave' @leave='leave'> // 插槽 <slot v-if='show'></slot> </transition>`, methods: { // 进入时 beforeEnter: function(el) { el.style.opacity = 0; }, enter: function(el, done) { Velocity(el, { opacity: 1 }, { duration: 1000, // complete: done }); }, // 离开时 beforeLeave: function(el) { el.style.opacity = 1; }, leave: function(el, done) { Velocity(el, { opacity: 0 }, { duration: 1000, complete: done }); }, afterLeave: function(el) { el.style.display = 'none'; } } }); // 实例化Vue var vm = new Vue({ el: '.app', data: { show: true }, methods: { btnClick: function() { this.show = !this.show; } } }); </script> </body> </html>