vue在insert前加class,留着

Vue add class before insert, leave it

我有一个自定义动画,常规 Vue transition 没有完全涵盖。我在其他地方用条件 v-bind:class 实现了它,但这对条件 v-if 块或 v-for 组来说效果不佳。

我需要在输入元素后的一帧添加一个 class ('open'),就像 v-enter-to 一样,但我需要它永远不会从元素中删除。

然后我需要在离开时将其移除以触发关闭动画。

我使用 Vue Transition 是不是错了,这在 transition 中是完全可能的,或者有没有办法 add/remove class 围绕 enter/leave 功能?

.accordion {
    overflow: hidden;

    > div {
        margin-bottom: -1000px;
        transition: margin-bottom .3s cubic-bezier(.5,0,.9,.8),visibility 0s .3s,max-height 0s .3s;
        max-height: 0;
        overflow: hidden;
    }

    &::after {
        content: "";
        height: 0;
        transition: height .3s cubic-bezier(.67,.9,.76,.37);
        max-height: 35px;
    }

    &.open {
        max-height: 8000px;

        > div {
            transition: margin-bottom .3s cubic-bezier(.24,.98,.26,.99);
            margin-bottom: 0;
            max-height: 100000000px;
            position: relative;
        }

        &::after {
            height: 35px;
            max-height: 0;
            transition: height .3s cubic-bezier(.76,.37,.67,.9),max-height 0s .3s;
        }
    }
}
<transition name="accordion" :duration="300">
  <div class="accordion" v-if="equipmentSelections.length === 0">
    <div>
      <p>Begin by selecting equipment from the list</p>
    </div>
  </div>
 </transition>
 
<transition-group name="accordion" :duration="300">
  <div v-for="equipment in equipmentSelections" v-bind:key="equipment.unitNumber" class="accordion">
    <div>
      <h3 v-on:click="updateSelections(equipment)">{{equipment.unitNumber}}</h3>
    </div>
  </div>
</transition-group>

您可以使用 javascript 挂钩从 vue 转换组件中获得更多功能。

例如: 演示:https://codepen.io/KingKozo/pen/QWpBPza

HTML:

<div id="app">
  <div>
    <button type="button" @click="toggle">Toggle</button>
  </div>
  <transition name="label" v-on:enter="enter" v-on:before-leave="leave">
    <div v-if="isOpen">Hi</div>
  </transition>
</div>

CSS

.label-enter-active, .label-leave-active {
  transition: opacity 1s;
}
.label-enter, .label-leave-to /* .fade-leave-active below version 2.1.8 */ {
  opacity: 0;
}

.staying-visible {
  background-color: red;
  color: white;
}

Javascript

const vm = new Vue({
  el: '#app',
  data: {
    isOpen: false
  },
  methods: {
    enter(el){
      el.classList.add("staying-visible")
    },
    leave(el){
      el.classList.remove("staying-visible")
    },
    toggle(){
      this.isOpen = !this.isOpen
    }
  }
})

在我提供的示例中,我添加了一个全新的 class、“保持可见”到输入时的元素,稍后将其删除。在提供的示例中,我删除了“离开前”的 class 以使更改可见,但对于您的特定用例,您似乎也可以在 'leave' 挂钩期间将其删除。

要了解有关如何使用 javascript 转换挂钩的更多信息,请查看官方文档:https://vuejs.org/v2/guide/transitions.html#JavaScript-Hooks