如何在没有硬编码高度的情况下使用Vue.js过渡?

时间:2017-12-28 20:14:39

标签: css vue.js transition

我有一个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中的高度进行硬编码的情况下使动画工作?

1 个答案:

答案 0 :(得分:0)

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

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