Seamlessly revitalize v-show in VueJS

I tried to animate two divs using the transition in Vuejs. Below is the code (jsfiddle) that I used. But I donโ€™t know why it doesnโ€™t work.

https://jsfiddle.net/k6grqLh1/16/

vu

<div id="vue-instance"> <div> <transition name="fade"> <div v-show="show"> <div class="box yellow"></div> </div> </transition> <transition name="fade"> <div v-show="!show"> <div class="box blue"></div> </div> </transition> <a href="#" @click="show = !show">Change</a> </div> </div> 

CSS

 .fade-enter-active, .fade-leave-active { transition: opacity .5s } .fade-enter, .fade-leave-to /* .fade-leave-active in <2.1.8 */ { opacity: 0 } .box { width:200px;height:200px; } .yellow{ background-color:yellow; } .blue{ background-color:blue; } 

Js

 var vm = new Vue({ el: '#vue-instance', data: { show: true } }); 
+5
source share
3 answers

You must add a key to each div, in addition to adding vue 2.x in the fiddle, you need to make the following changes:

Why from docs

When switching between elements that have the same tag name, you must tell Vue that they are separate elements, providing them with unique key attributes. Otherwise, the Vues compiler will only replace the contents of the element with efficiency. Even when this is not technically necessary, its prudent practice should always include several elements within the component.

HTML

 <transition name="fade"> <div key="3" v-if="show"> <div class="box yellow"></div> </div> </transition> <transition name="fade"> <div key="1" v-if="!show"> <div class="box blue"></div> </div> </transition> 

Working fiddle: https://jsfiddle.net/k6grqLh1/21/

Edited

To make it smoother, you can use Transition-Modes : mode="out-in" , which first displays the current element, then when the full, new element goes to. see below code:

 <transition name="fade" mode="out-in"> <div key="3" v-if="show"> <div class="box yellow"></div> </div> <div key="1" v-if="!show"> <div class="box blue"></div> </div> </transition> 

Fiddle: https://jsfiddle.net/k6grqLh1/22/

+10
source

I would definitely suggest using: https://github.com/asika32764/vue2-animate

Great library with AnimateCSS ported to VueJS transitions. I use this with every project and it works great.

To use it with v-show with one item:

 <transition name="fade" > <p v-if="show">hello</p> </transition> 
+2
source

First of all .. you import Vue 1. If you import Vue 2, this html works

 <div id="vue-instance"> <div> <transition name="fade"> <div v-if="show" key="yellow"> <div class="box yellow"></div> </div> <div v-if="!show" key="blue"> <div class="box blue"></div> </div> </transition> <a href="#" @click="show = !show">Change</a> </div> </div> 

Then you should read the docs https://vuejs.org/v2/guide/transitions.html#Transitioning-Between-Elements if you want to see how transitions between elements are handled

+1
source

Source: https://habr.com/ru/post/1263770/


All Articles