Reputation: 2301
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.
Upvotes: 41
Views: 43899
Reputation: 2279
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/
Upvotes: 11
Reputation: 18834
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>
Upvotes: 82
Reputation: 5791
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" ...
Upvotes: 5