【问题标题】:How to animate height of transition-group container in Vue如何在Vue中为transition-group容器的高度设置动画
【发布时间】:2020-12-19 08:50:01
【问题描述】:

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

CodeSandbox

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

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

问候

【问题讨论】:

    标签: css vue.js vuejs2 transition


    【解决方案1】:

    只需将 CSS 属性添加到您的容器:transition: .3s 其中 3s 是转换时间的值并动态更改容器的高度。

    【讨论】:

    • 根据您的情况处理和设置容器动态高度的最佳方法是什么。
    • v-bind 我认为的样式属性
    • 当然,为此我们必须添加最大高度,对吗?为此,我如何计算元素的高度?
    • 我明白了。看这个例子:jsfiddle.net/nthk0myo 只需为你添加的元素设置静态高度。
    • 感谢您的想法。它在我的脑海中,但我不知道为什么我没有尝试。顺便说一句,任何人将来在现实世界使用中检查这一点,我正在使用 this.$refs.thatElement.offsetHeight 计算元素的高度并将其添加到高度。
    【解决方案2】:
    <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 元素的高度

    在你的 div 中添加一个 css 类

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

    【讨论】:

    • 这很好,但可以改进吗?因为p 标签在实际应用中不能有固定的高度。另外,没有像height 100vh这样的补丁可以吗?
    猜你喜欢
    • 2020-07-04
    • 1970-01-01
    • 2019-07-07
    • 2017-07-24
    • 1970-01-01
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多