无法使Vue.js过渡正常工作

时间:2019-01-27 16:35:43

标签: vue.js transition

我有一个通过v-for显示的项目列表。默认情况下,仅显示每个项目的摘要部分。单击某个项目时,将显示该项目的详细信息部分。

这是通过添加/删除active类并在项目的详细信息部分上切换display: block / display: none来实现的。

现在,我想添加平滑的过渡。我关注了the first example in the docs。但是我不知道如何使它按预期工作。目前过渡根本无法进行:点击该项目时,详细信息部分会立即显示,而再次单击时,该信息部分会立即消失。

我的代码怎么了?

    .event-details {
      display: none;
    }
    
    .event.active .event-details-enter-active,
    .event.active .event-details-leave-active {
      transition: opacity .5s;
      transition: height .5s;
    }
    
    .event.active .event-details-enter,
    .event.active .event-details-leave-to {
      opacity: 0;
      display: none;
      height: 0;
    }
    
    .event.active .event-details-enter,
    .event.active .event-details-leave-to {
      opacity: 1;
      display: block;
      height: auto;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<li :class="{ active: event.active }" v-for="event in events" @click="showEvent(event)">
      <div class="event-summary">
        content
      </div>
      <transition name="event-details">
        <div class="event-details">
          content
        </div>
      </transition>
    </li>

编辑:这是事件数组的console.log

enter image description here

1 个答案:

答案 0 :(得分:1)

您应按如下所示向由v-if包裹的元素中添加transition指令

new Vue({
  el: '#app',
  data() {
    return {
      events: [{
          active: false,
          city: "new york"
        },
        {
          active: false,
          city: "Algiers"
        },
        {
          active: false,
          city: "Paris"
        },
        {
          active: false,
          city: "Madrid"
        },

      ]
    };

  },
  methods: {
    showEvent(index) {
      this.events[index].active = !this.events[index].active;
    }

  }

})
.event-details{
padding:20px;
color:#55ff44
}
.slide-fade-enter-active {
  transition: all .8s ease;
}
.slide-fade-leave-active {
  transition: all .8s cubic-bezier(1.0, 0.5, 0.8, 1.0);
}
.slide-fade-enter, .slide-fade-leave-to
/* .slide-fade-leave-active below version 2.1.8 */ {
  transform: translateX(10px);
  opacity: 0;
}
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <ul>
    <li :class="{ active: event.active }" v-for="(event,index) in events" @click="showEvent(index)">
      <div class="event-summary">
        {{event.city}}
      </div>
      <transition name="slide-fade">
        <div class="event-details" v-if='event.active'>
          some content
        </div>
      </transition>
    </li>
  </ul>
</div>