Vue transitions are used to apply animations when an element or component is entering and leaving the DOM. These animations are triggered by:
v-ifv-show<component> special elementkey attributeThe key attribute is handy if you need to trigger your transition programmatically. One use case for programmatically triggering Vue transitions is in form validation. By dynamically triggering transitions based on the validity of form inputs, users can receive visual feedback in real-time, enhancing the overall user experience and guiding them through the form submission process with clarity and ease.
Let's take a look at a simple example of how to trigger a transition programmatically:
<script setup lang="ts">
import { ref } from 'vue';
const show = ref(false);
const animationTrigger = ref(0);
</script>
<template>
<div class="container">
<Transition name="slide-fade">
<p v-if="show" :key="animationTrigger">Hi</p>
</Transition>
<button @click="show = !show">Toggle</button>
<button @click="animationTrigger += 1">
Re-trigger animation ({{ animationTrigger }})
</button>
</div>
</template>
Try it yourself in the following StackBlitz:
If you liked this Vue tip, follow me on Twitter to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter :
