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-
enter-from-
enter-to-
leave-active-
leave-from-
leave-to-
>
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
CodePudding user response:
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" >Toggle</button>
<div>
<!-- Modal background -->
<transition
appear
enter-active-
enter-from-
enter-to-
leave-active-
leave-from-
leave-to-
>
<div v-if="show" ></div>
</transition>
<!-- Modal content -->
<transition
appear
enter-active-
enter-from-
enter-to-
leave-active-
leave-from-
leave-to-
>
<div v-if="show" >
<h2 >test</h2>
</div>
</transition>
</div>
</div>
<script src="https://unpkg.com/vue@3"></script>
<script src="https://cdn.tailwindcss.com"></script>