Vue.js leave animation not working as expected

Viewed 293

The demo is quite simple, and similar to the example in the Vue.js docs.

new Vue({
  el: '#demo',
  data: {
    show: true
  }
})
p {
  width: 100px;
  border: 1px solid red;
}

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

.fade-enter {
  opacity: 0;
  width: 500px;
  background: red;
}

.fade-enter-to {
  background: black
}

.fade-leave {
  opacity: 0;
  background: red
}

.fade-leave-to {
  background: black;
  width: 1000px;
  opacity: 1
}
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12"></script>
<div id="demo">
  <button v-on:click="show = !show">
    Toggle
  </button>
  <transition name="fade">
    <p v-if="show">hello</p>
  </transition>
</div>

The question is, when the leave animation begins, it seems it's removed from the DOM (v-if is false) so quickly that there isn't any animation at all!

But, if I remove opacity, the animation works! Why does opacity matter?

.fade-leave {
  /* opacity: 0; */
  background: red;
} 

.fade-leave-to {
  background: black;
  width: 1000px;
  /* opacity:1; */
}

There is another question, I thought the leave animation should be that the DOM background becomes red firstly (while the result is it didn't or I just can't tell), then change to black slowly. So, is it my misconception?

1 Answers

The opacity is important because the animation is fading according to it.

Here I have added to opacity of 0 directly to the class fade-enter-active of the button Hello. You can see the animation fading step by step.

enter image description here

Instead, with an opacity of 1, there is no direction to your fading. It stays at 1.

Related