Vue中的动画封装
以下代码是实现点击按钮使文字渐隐渐现的隐藏和显示的功能:
DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Vue中的进场和出场过渡title>
<script src="./vue.js">script>
<style>
.v-enter,
.v-leave-to{
opacity:0;
}
.v-enter-active,
.v-leave-active{
transition: opacity 1s;
}
style>
head>
<body>
<div id="root">
<transition>
<div v-if="show">hello worlddiv>
transition>
<button @click="handleClick">togglebutton>
div>
<script >
var vm = new Vue({
el:'#root',
data:{
show:true
},
methods:{
handleClick:function() {
this.show =!this.show
}
}
})
script>
body>
html>
对应常用的动画效果,可以将其进行封装起来,供其他模块调用,降低重复打码的开发。
使用要封装的内容写成组件,并用slot插槽接管组件内容,就能实现动画封装了。代码如下:
<div id="root"> <fade :show="show"> <div>hello worlddiv> fade> <button @click="handleClick">togglebutton> div> Vue.component('fade',{ props:['show'], template:`<transition name="fade"> <slot v-if="show">slot> transition>` })
动画封装不仅可以封装内容也可以封装动画样式,这时候就不需要CSS样式而是使用JS动画将其一起封装在组件里。代码如下:
Vue.component('fade', { props: ['show'], template: ` <transition
@before-enter="handleBeforeEnter" @enter="handleEnter" @after-enter="handleAfterEnter"> <slot v-if="show">slot> transition> `, methods: { handleBeforeEnter: function(el) { el.style.color = 'red' }, handleEnter: function(el, done) { setTimeout(() => { el.style.color = 'green' done() }, 2000) }, handleAfterEnter: function(el) { el.style.color = '#000' } } })
上面代码用了JS提供的钩子动画before-enter、enter、after-enter,用这种方法写,所有的动画都写在了组件里,外部只需要调用这个fade组件就可以了,也不需要全局去写一些样式了,这种动画的封装是比较推荐的一种动画封装,因为它可以把所有动画的实现完整的封装在一个组件中。
参考文章:https://segmentfault.com/a/1190000018130259