38

Is there a way that you can use transition between vuejs conditionals v-if and v-else?

As an example:

<transition name="fade">
    <p v-if="show">hello</p>
    <p v-else>Goodbye</p>
</transition>

new Vue({
   el: '#demo',
   data: {
       show: true
   }
})

.fade-enter-active,
.fade-leave-active {
    transition: opacity .5s
 }

.fade-enter,
.fade-leave-active {
    opacity: 0
}

I can't seem to get a transition to work in such a scenario, where, as you toggle show, the <p> elements use a transition between them.

https://jsfiddle.net/fbponh78

3 Answers 3

79

Your problem is caused by the fact that vue transition does not see the element change, it only sees the content change.

This is caused by the fact that both elements have the same tag name, so vue just reuses this. To counteract this, give both elements an differed key value:

<p key=1 v-if="show">hello</p>
<p key=2 v-else>Goodbye</p>

Example:

new Vue({
    el: '#demo',
    data: {
        show: true
    }
});
.fade-enter-active,
.fade-leave-active {
    transition: opacity .5s
}

.fade-enter,
.fade-leave-to {
    opacity: 0
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>

<div id="demo">
    <button v-on:click="show = !show">
        Toggle
    </button>
    <transition name="fade">
        <p key=1 v-if="show">hello</p>
        <p key=2 v-else>Goodbye</p>
    </transition>
</div>

3
  • 4
    If you're lazy you can also set a key on only 1 element, it'll still work.
    – Eric Guan
    Aug 14, 2018 at 7:35
  • 21
    Dont forget transition mode to prevent Simultaneous entering and leaving like this: <transition name="fade" mode="out-in"> Nov 12, 2018 at 14:41
  • 1
    @Ferribig , do you mind explaining this solution? Thanks for all this info btw! Feb 20, 2019 at 5:27
11

Use two transitions:

new Vue({
  el: '#demo',
  data: {
    show: true
  }
})
.fade-enter-active {
  transition: opacity .5s
}

.fade-enter,
.fade-leave-active {
  opacity: 0
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>

<div id="demo">
  <button v-on:click="show = !show">
    Toggle
  </button>
  <transition name="fade">
    <p v-if="show">hello</p>
  </transition>
  <transition name="fade">
    <p v-if="!show">Goodbye</p>
  </transition>
</div>

https://jsfiddle.net/saeedahmadi/fbponh78/10/

2

I had a problem, where a complex component would make v-else enter before v-if was removed. What helped me was @Khalil's (comments) suggestion:

<transition mode="out-in" ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.