在做一个项目过程中,可能会出现多个重复动画,这样反复的使用 <transition>
包裹 DOM 元素实现动画显然是不合理的。为了解决这个问题,我们可以利用 插槽 <slot>
传递DOM元素的特点实现动画的封装,多处复用的效果!
1.动画封装模板
CommonAnimation.vue
注意:不要忘记使用
props: ['show']
接收传值
<template>
<transition
@before-enter="handleBeforeEnter"
@enter="handleEnter"
@after-enter="handleAfterEnter"
>
<slot v-if="show"></slot>
</transition>
</template>
<script>
export default {
props: ['show'],
methods: {
handleBeforeEnter(el) {
el.style.color = 'red';
},
handleEnter(el, done) {
setTimeout(() => {
el.style.color = 'green';
}, 2000);
setTimeout(() => {
done()
}, 4000);
},
handleAfterEnter(el) {
el.style.color = 'black';
}
}
}
</script>
2.使用动画封装模板
Animate.vue
注意:传值写法
:show="show"
<template>
<div id="root">
<v-animation :show="show">
<div>hello world</div>
</v-animation>
<v-animation :show="show">
<h1>hello world</h1>
</v-animation>
<button @click="toggle">切换</button>
</div>
</template>
<script>
import CommonAnimation from "./CommonAnimation.vue";
export default {
data() {
return {
show: true
}
},
methods: {
toggle() {
this.show = !this.show;
}
},
components: {
"v-animation": CommonAnimation
}
}
</script>