Vue 实现高度过渡

方法一:自己封装一个高度过渡组件

Vue的 <transition> 组件是实现不了元素高度过渡的,所以我们可以自己封装一个高度过渡组件。  

组件的原理是:使用原生的 CSS3  transition 属性,在改变元素的高度的同时会有过渡效果。 

这里有个注意点,显示的时候为什么元素的高度要赋值为 offsetHeight 的高度,而不能设置成 auto?

原因是 CSS3  transition 属性不支持 height 为 auto 的过渡。

以下是组件的封装代码:

<template>
  <div class="container" ref="container">
    <slot></slot>
  </div>
</template>

<script>
export default {
  props: {
    show: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      height: 0,
    };
  },
  mounted() {
    this.$nextTick().then(() => {
      this.height = this.$refs.container.offsetHeight;
      this.$refs.container.style.height = this.show ? `${this.height}px` : 0;
    });
  },
  watch: {
    show(newVal) {
      this.$refs.container.style.height = newVal ? `${this.height}px` : 0;
    },
  },
};
</script>

<style scoped>
.container {
  transition: height .5s linear;
  overflow: hidden;
}
</style>

使用组件:

<template>
  <div>
    <a @click="show = !show">切换</a>

    <TransitionHeight :show="show">
        内容
    </TransitionHeight>
  </div>
</template>

<script>
import TransitionHeight from './components/transition-height.vue';

export default {
  components: {
    TransitionHeight,
  },
  data() {
    return {
      show: true,
    }
  },
}
</script>

方法二:使用 Element UI 的折叠面板组件

如果你的项目当中刚好使用了 Element 组件库,你就直接使用折叠面板组件就好了,其他组件库应该也有对应的这种过渡效果,组件文档里找一下就OK了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值