Javascript is required
ยท
1 min read

Vue Tip: Trigger Transition Programmatically

Vue Tip: Trigger Transition Programmatically Image

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:

Component.vue
1<script setup lang="ts">
2import { ref } from 'vue';
3
4const show = ref(false);
5
6const animationTrigger = ref(0);
7</script>
8
9<template>
10  <div class="container">
11    <Transition name="slide-fade">
12      <p v-if="show" :key="animationTrigger">Hi</p>
13    </Transition>
14    <button @click="show = !show">Toggle</button>
15    <button @click="animationTrigger += 1">
16      Re-trigger animation ({{ animationTrigger }})
17    </button>
18  </div>
19</template>

StackBlitz

Try it yourself in the following StackBlitz:

If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.