In Vue.js, transitions allow you to apply effects when elements are inserted, updated, or removed from the DOM. Vue provides a transition system that can be used with CSS classes or JavaScript hooks. Here's a guide on how to handle transitions in Vue.js:
Create CSS classes for the transition effect. Vue.js will automatically add these classes during different stages of the transition.
css/* fade-in transition */
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
transition
Wrapper:Wrap the element you want to transition with the transition
component.
html<template>
<transition name="fade">
<p v-if="show">Hello, Vue.js!</p>
</transition>
</template>
<script>
export default {
data() {
return {
show: true
};
}
};
</script>
You can use JavaScript hooks for more control. Here's an example using beforeEnter
, enter
, and leave
hooks.
html<template>
<transition
@before-enter="beforeEnter"
@enter="enter"
@leave="leave"
>
<p v-if="show">Hello, Vue.js!</p>
</transition>
</template>
<script>
export default {
data() {
return {
show: true
};
},
methods: {
beforeEnter(el) {
el.style.opacity = 0;
},
enter(el, done) {
el.offsetHeight; // trigger reflow
el.style.transition = "opacity 0.5s";
el.style.opacity = 1;
done();
},
leave(el, done) {
el.style.transition = "opacity 0.5s";
el.style.opacity = 0;
done();
}
}
};
</script>