Vue Accordion with transition

时间:2017-12-03 08:36:56

标签: vue.js vuejs2 vue-component

我正在尝试将Accordion组件与主体转换集成,但没有成功:(。除动画外,所有内容都正常。

模板:

  <div class="accordion">
    <div class="accordion-title" @click="isOpen = !isOpen" :class="{'is-open': isOpen}">
      <span>{{title}}</span>
      <i class="ic ic-next"></i>
    </div>
    <div class="accordion-body" :class="{'is-open': isOpen}">
      <div class="card">
        <slot name="body"></slot>
      </div>
    </div>
  </div>

组件:

  props: {
    title: {
      type: String,
      default: 'Title'
    }
  },
  data() {
    return {
      isOpen: false
    }
  }

和样式:

.accordion-body {
  font-size: 1.3rem;
  padding: 0 16px;  
  transition: .3s cubic-bezier(.25,.8,.5,1);  
  &:not(.is-open) {
    display: none;
    height: 0;
    overflow: hidden;
  }
  &.is-open {
    height: auto;
    // display: block;
    padding: 16px;
  }
}

.card {
  height: auto;
}

我尝试使用<transition>,但它不适用于heightdisplay属性。 求救!

1 个答案:

答案 0 :(得分:0)

display:none会删除您的内容并避免动画,您应该使用opacityoverflow:hiddenheight进行操作,但是您将被迫为此做一个方法

例如(未经测试,但鼓舞人心):

模板中的

<div class="accordion" @click="switchAccordion" :class="{'is-open': isOpen}">
  <div class="accordion-title">
    <span>{{title}}</span>
    <i class="ic ic-next"></i>
  </div>
  <div class="accordion-body">
    <p></p>
  </div>
</div>
组件中的

(添加方法):

  methods: {
    switchAccordion: function (event) {
      let el = event.target
      this.isOpen = !this.isOpen // switch data isOpen
      if(this.isOpen) {
        let childEl1 = el.childNodes[1]
        el.style.height = childEl1.style.height
      } else {
        let childEl2 = el.childNodes[2]
        el.style.height = childE2.style.height // or .clientHeight + "px"
      }  
    }
  }
风格

.accordion {
  transition: all .3s cubic-bezier(.25,.8,.5,1);
} 

.accordion-body {
  font-size: 1.3rem;
  padding: 0 16px; 
  opacity:0
}

.is-open .accordion-body {
  opacity:0
}

在这种情况下,您的转换应该可以按照您的意愿运行。 javascript将更改高度值,转换transition: all .3s cubic-bezier(.25,.8,.5,1);将执行动画