VUE transition实现展开/收起高度不确定的元素

2020-04-08  本文已影响0人  努力努力再努力_g

最近遇到一个需求,循环展示列表,每个列表要有收起和展开的功能,由于每个列表的高度不确定,在写vue-transition的时候遇到了问题。


image.png

正常实现展开收缩的方法

<!--css-->
原链接  [https://www.jianshu.com/p/6cd79c029167](https://www.jianshu.com/p/6cd79c029167)
作者:[xilong](https://www.jianshu.com/u/fdd91ad87feb)


.box{
    height:200px;width: 200px;
    background-color:black;
}
.draw-enter-active, .draw-leave-active {
    transition: all 1s ease;
}
.draw-enter, .draw-leave-to /* .fade-leave-active below version 2.1.8 */ {
    height: 0;
}

<div id="app">
    <button @click="boxshow = !boxshow">点击展开/关闭</button>
    <transition name="draw">   <!--这里的name 和 css 类名第一个字段要一样-->
        <div class="box"  v-show="boxshow"></div>
    </transition>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<script>
    new Vue({
        el:'#app',
        data:{
            boxshow:false
        },
    });
</script>

实现高度自适应的收缩和展开

参考原链接:https://segmentfault.com/a/1190000021856837
作者:oranges_c (关注他!!!!!!!帮我节省了好长时间)

我一开始想参考element-ui 中 collapse 的处理方式,源码也可以拿来用,后来上述作者给的处理方法也能正常使用,就没再看源码。以下是处理方式

collapse-transition.js,这个文件我是放在utils工具类中的

const transitionStyle = '0.3s height ease-in-out'
const Transition = {
  beforeEnter (el) {
    el.style.transition = transitionStyle
    if (!el.dataset) el.dataset = {}

    el.style.height = 0
  },

  enter (el) {
    if (el.scrollHeight !== 0) {
      el.style.height = `${el.scrollHeight}px`
    } else {
      el.style.height = ''
    }
    el.style.overflow = 'hidden'
  },

  afterEnter (el) {
    el.style.transition = ''
    el.style.height = ''
  },

  beforeLeave (el) {
    if (!el.dataset) el.dataset = {}
    el.style.height = `${el.scrollHeight}px`
    el.style.overflow = 'hidden'
  },

  leave (el) {
    if (el.scrollHeight !== 0) {
      el.style.transition = transitionStyle
      el.style.height = 0
    }
  },

  afterLeave (el) {
    el.style.transition = ''
    el.style.height = ''
  }
}

export default {
  name: 'CollapseTransition',
  functional: true,
  render (h, {
    children
  }) {
    const data = {
      on: Transition
    }
    return h('transition', data, children)
  }
}

页面中使用方法
 <div class="expand">
        <div v-if="!boxshow"
             class="flex"
             @click="boxshow = !boxshow">
          <span>展开</span>
          <i class="h-icon-angle_down"></i>
        </div>
        <div v-if="boxshow"
             class="flex"
             @click="boxshow = !boxshow">
          <span>收起</span>
          <i class="h-icon-angle_up"></i>
        </div>
   </div>

<collapse-transition>
  <div class="cashbox-body expandBox"
           v-if="boxshow">
你的具体内容放在这里
</div>
</collapse-transition>

import CollapseTransition from '@/utils/collapse-transition'
export default {
  components: {
    'collapse-transition': CollapseTransition
  },
  data () {
    return {
      boxshow: true
    }
  }
}

原链接写的更详细,各位可以参考原链接哦!

上一篇下一篇

猜你喜欢

热点阅读