Search code examples
vue.jstransitionvuejs2

vue2 transition between two div elements


I found that the transition doesn't work between two div elements as following:

<transition name="fade">
  <div v-if="show">111</div>
  <div v-else>222</div>
</transition>

but it works if there is only one div element like:

<transition name="fade">
  <div v-if="show">111</div>
  <p v-else>222</p>
</transition>

is that a vue 2 bug ? or I just can't use it with two div elements?

How to do it with two div elements ..?


Solution

  • You should add unique key attribute to divs in order to make it work: https://jsfiddle.net/a8fv6rvp/1/

    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    
    <div id="app">
      <transition name="fade" mode="out-in">
        <div v-if="show" key="1">111</div>
        <div v-else key="2">222</div>
      </transition>
      <button @click="show = !show">Toggle</button>
    </div>
    
    new Vue({
        el: '#app',
      data: {
        show: true
      }
    });
    
    <style>
    .fade-enter-active, .fade-leave-active {
      transition: opacity .5s
    }
    .fade-enter, .fade-leave-to {
      opacity: 0
    }
    </style>