Can’t animate v-if by using transition-group

I have usually found that transitions only work when I wrap the element with v-if directly inside the transition. so something like this will work

<template>
  <div id="app">
    <h1>Sample Animation App</h1>
    <transition-group name="fade" mode="out-in">
      <p v-if="chosenValue===0" key="234">First</p>
      <p v-if="chosenValue===1" key="6544">Scond</p>
      <p v-if="chosenValue===2" key="678">Third</p>
    </transition-group>
    <button @click="changeVal">Update</button>
  </div>
</template>

<script>

export default {
  name: "App",
  data(){
    return {
      chosenValue:""
    }
  },
  methods:{
    changeVal(){
      this.chosenValue= Math.floor(Math.random()*3);
    }
  }
};
</script>

<style>
.fade-enter-active, .fade-leave-active {
  transition: all 200ms;
}

.fade-enter, .fade-leave-to {
  opacity: 0;
}
</style>

If however, I change the code so that v-if is managed inside my individual components, something like so:

<template>
  <div id="app">
    <h1>hsahaha</h1>
    <transition-group name="fade" mode="out-in">
      <custom-component key="234">First</p>
      <custom-component key="6544">Scond</p>
      <custom-component key="678">Third</p>
    </transition-group>
    <button @click="changeVal">Update</button>
  </div>
</template>

<style>
.fade-enter-active, .fade-leave-active {
  transition: all 200ms;
}

.fade-enter, .fade-leave-to {
  opacity: 0;
}
</style>

This will not work because transition-group doesn’t directly know about the internal state of the custom-component.

So, in your case, if you wrap each individual profileProgressContent component with a transition, it should work.

<template>

 <transition name="fade">
  <div v-if="!finished" :key="step.progress">
    <span @click="finishStep()">
      {{ step.label }}
    </span>
  </div>
 </transition>
</template>

<style>
.fade-enter-active, .fade-leave-active {
  transition: all 200ms;
}

.fade-enter, .fade-leave-to {
  opacity: 0;
}
</style>

General Rule of Thumb I follow is:

For all components inside a transition-group, keep v-if on each one of them in the same file as the transition-group itself

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top