如何在不对高度进行硬编码的情况下使用 Vue.js 过渡?

How can I use Vue.js transitions without hard coding height?

我有一个 Vue 应用程序,其中有一个元素需要通过单击按钮展开和折叠。效果需要动画化以减少不和谐感。我为此使用了 <transition> 标签,但它不起作用,除非我在 css 中硬编码元素的 height 属性。这将不起作用,因为该元素包含动态数据并且具有不同的高度。

这是我的代码:

<template>
    <input type="button" value="Toggle" v-on:click="showIt = !showIt"/>
    <transition name="test-tran">
        <div class="test-block" v-show="showIt">
            <div v-for="item in items">{{ item }}</div>
        </div>
    </transition>
</template>

<script>
    export default {
        data() {
            return {
                showIt: false
            };
        }
    }
</script>

这里是对应的css:

.test-block {
    /*
    adding a height makes the transition work but
    an accurate height can't be known ahead of time

    height: 100px;
    */
}

.test-tran-enter-active {
    transition: all .5s ease;
}

.test-tran-leave-active {
    transition: all .5s ease;
}

.test-tran-enter, .test-tran-leave-to
    height: 0;
}

.test-tran-leave, .test-tran-enter-to
    /*
    adding a height makes the transition work but
    an accurate height can't be known ahead of time

    height: 100px;
    */
}

如果没有 height 属性,元素会正确显示和隐藏,但没有动画。它只是出现并立即消失。

如何在不对 css 中的高度进行硬编码的情况下使动画工作?

不,这是一个纯粹的 css 问题。为了过渡到工作高度,必须提供。不过你可以用一种 hacky 的方式解决它。

How can I transition height: 0; to height: auto; using CSS?