<template>
<div :style="{'max-height': list.length * 24 + 'px'}" class="dynamic-height 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: "DynamicList",
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%);
}
.dynamic-height {
height: 100vh;
transition: max-height 300ms;
}
.fade-top-leave-to {
opacity: 0;
transform: translateY(-8%);
}
</style>
When implementing height transitions, consider using max-height
. Begin by setting a large height such as 100vh
, then calculate the max-height
based on the length of your list.
:style="{'max-height': list.length * 24 + 'px'}"
If you're wondering about the value "24", it represents the height of your p
element.
Additionally, apply a CSS class to your div:
.dynamic-height {
height: 100vh;
transition: max-height 300ms;
}