Vue3的transition标签以及animate.css使用详解
<template>
<div id="app">
<button @click="show = !show">Toggle</button>
<transition name="fade" @before-enter="beforeEnter" @enter="enter" @after-enter="afterEnter">
<div v-if="show" class="box"></div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
show: true
}
},
methods: {
beforeEnter(el) {
el.style.opacity = 0;
el.style.transition = 'opacity 0.5s';
},
enter(el, done) {
setTimeout(() => {
el.style.opacity = 1;
}, 100);
setTimeout(done, 500);
},
afterEnter(el) {
this.animateCSS(el, 'animate__animated', 'animate__bounceIn');
},
animateCSS(element, animationName, animationType) {
const node = document.createElement('div');
node.classList.add(animationName);
node.classList.add(animationType);
node.classList.add('hide');
element.appendChild(node);
function handleAnimationEnd(event) {
event.stopPropagation();
node.classList.remove(animationType);
node.classList.remove('hide');
node.removeEventListener('animationend', handleAnimationEnd);
}
node.addEventListener('animationend', handleAnimationEnd);
}
}
}
</script>
<style>
.box {
width: 100px;
height: 100px;
background-color: red;
}
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active for <2.1.8 */ {
opacity: 0;
}
</style>
这个示例代码展示了如何在Vue 3中使用transition标签以及如何使用自定义的JavaScript动画函数来替代CSS动画库(如animate.css)的某些动画效果。这样做的好处是可以更灵活地控制动画的行为,并且不需要依赖外部的CSS文件。
评论已关闭