Vue Tip: Trigger Transition Programmatically
Michael Hoffmann
@mokkapps
Vue transitions are used to apply animations when an element or component is entering and leaving the DOM. These animations are triggered by:
- Conditional rendering via
v-if
- Conditional display via
v-show
- Dynamic components toggling via the
<component>
special element - Changing the special
key
attribute
The 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.
Example Code
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>
StackBlitz
Try it yourself in the following StackBlitz:
If you liked this Vue tip, follow me on BlueSky to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter :