如何在 Vue 中设置过渡组容器的高度动画

How to animate height of transition-group container in Vue

我正在尝试在列表中添加和删除项目。我可以为列表设置动画,但容器的高度没有设置动画。

CodeSandbox

正如您在预览中看到的,红色容器在没有过渡的情况下获得和失去高度。

如何在添加或删除项目时为容器的高度设置动画?

此致

<template>
  <div :style="{'max-height': list.length * 24 + 'px'}" class="hgh bg-red-400 container mx-auto">
    <transition-group name="fade-top" tag="ul">
      <li v-for="(item, index) in list" :key="index">
        <p>{{ item }}</p>
      </li>
    </transition-group>
    <button class="mt-4 px-5 py-2 bg-indigo-400 text-white" @click="add">Add</button>
    <button class="mt-4 ml-4 px-5 py-2 bg-indigo-400 text-white" @click="remove">Remove</button>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      list: [1, 2, 3, 4]
    };
  },
  methods: {
    add() {
      this.list.push(Math.round(Math.random() * 10));
    },
    remove() {
      this.list.pop();
    }
  }
};
</script>
<style>
.fade-top-enter-active,
.fade-top-leave-active {
  transition: opacity 0.3s, transform 0.35s;
}
.fade-top-enter {
  opacity: 0;
  transform: translateY(8%);
}
.hgh {
  height: 100vh;
  transition: max-height 300ms;
}
.fade-top-leave-to {
  opacity: 0;
  transform: translateY(-8%);
}
</style>

高度转换通常使用 max-height 完成。首先你设置一个像 100vh 这样的大高度,然后在你的 div 处根据你的列表长度

计算 max-height
:style="{'max-height': list.length * 24 + 'px'}"

如果你问 24 来自哪里,它是你的 p 元素的高度

同时添加一个 css class 到您的 div

.hgh {
  height: 100vh;
  transition: max-height 300ms;
}

只需将 CSS-attribute 添加到您的容器中:transition: .3s 其中 3s 是过渡时间的值并动态更改容器的高度。