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
If v-if == true and v-show changes from true to false , the leave transition occurs as expected. If v-show== true and v-if changes from true to false , the element is immediately removed, no transition occurs. My use case for this is using both v-if and v-show around media ( img , video ).
The key difference is that v-if conditionally renders elements and v-show **conditionally displays **elements. This means that v-if will actually destroy and recreate elements when the conditional is toggled. Meanwhile, v-show will always keep the element in the DOM and will only toggle its display by changing its CSS.
v-if - Only renders the element to the DOM if the expression passes. v-show - Renders all elements to the DOM and then uses the CSS display property to hide elements if the expression fails.
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://unpkg.com/vue/dist/vue.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>
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://unpkg.com/vue/dist/vue.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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With