Reputation: 98
I’m trying to create a ‘modal’ component. It’s using a ‘v-if’ attribute for deciding whether the component is shown or not.
The Vue docs mention you can use ‘appear’ for transitions (https://vuejs.org/guide/built-ins/transition.html#transition-on-appear), which works well.
However, when I close the modal, the element gets removed from the DOM, and the ‘leave’ transition is not trigged.
Is there an opposite of ‘appear’ for Vue transitions? How can I apply a leave transition when an element is removed from the DOM?
Link of example: https://jsfiddle.net/jelledv4/3Lr79hyg/4/
<transition
appear
enter-active-class="transition duration-1000 ease-out"
enter-from-class="transform scale-95 opacity-0"
enter-to-class="transform scale-100 opacity-100"
leave-active-class="transition duration-1000 ease-in"
leave-from-class="transform scale-100 opacity-100"
leave-to-class="transform scale-95 opacity-0"
>
PS I could use ‘v-show’ instead of ‘v-if’ to mitigate this, but for this use-case ‘v-if’ suits better. Plus I’m wondering how I can tackle this issue
Upvotes: 2
Views: 1546
Reputation: 1044
In your provided jsfiddle, you use v-if on the parent element of the Transition components. Instead, use v-if on the child/slot of the Transition component. Otherwise, the transition components will be removed immediately.
const app = Vue.createApp({
data() {
return {
show: false,
};
},
methods: {
toggle() {
this.show = !this.show;
},
}
});
app.mount('#app');
<div id="app">
<button @click="toggle" class="fixed z-10 bg-white ml-3 mt-3 border border-gray-800">Toggle</button>
<div>
<!-- Modal background -->
<transition
appear
enter-active-class="transition duration-1000 ease-out"
enter-from-class="opacity-0"
enter-to-class="opacity-100"
leave-active-class="transition duration-1000 ease-in"
leave-from-class="opacity-100"
leave-to-class="opacity-0"
>
<div v-if="show" class="absolute left-0 top-0 w-full h-full bg-black bg-opacity-50"></div>
</transition>
<!-- Modal content -->
<transition
appear
enter-active-class="transition duration-1000 ease-out"
enter-from-class="transform scale-95 opacity-0"
enter-to-class="transform scale-100 opacity-100"
leave-active-class="transition duration-1000 ease-in"
leave-from-class="transform scale-100 opacity-100"
leave-to-class="transform scale-95 opacity-0"
>
<div v-if="show" class="fixed bg-red-500 w-52 h-52 z-10 mt-14">
<h2 >test</h2>
</div>
</transition>
</div>
</div>
<script src="https://unpkg.com/vue@3"></script>
<script src="https://cdn.tailwindcss.com"></script>
Upvotes: 2