vue实现slidedown
Vue 实现 SlideDown 效果
SlideDown 是一种常见的动画效果,用于在元素从隐藏状态平滑展开到显示状态。在 Vue 中可以通过多种方式实现,包括使用 CSS 过渡、Vue 的内置过渡组件或第三方动画库。
使用 CSS 过渡和 Vue 的 v-if/v-show
通过 Vue 的 v-if 或 v-show 控制元素的显示与隐藏,结合 CSS 过渡实现 SlideDown 效果。
<template>
<div>
<button @click="toggle">Toggle Slide</button>
<transition name="slide">
<div v-if="isVisible" class="content">
This content will slide down and up.
</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
isVisible: false
};
},
methods: {
toggle() {
this.isVisible = !this.isVisible;
}
}
};
</script>
<style>
.slide-enter-active, .slide-leave-active {
transition: max-height 0.5s ease;
overflow: hidden;
}
.slide-enter-from, .slide-leave-to {
max-height: 0;
}
.slide-enter-to, .slide-leave-from {
max-height: 1000px; /* 设置为足够大的值 */
}
.content {
background: #f0f0f0;
padding: 10px;
margin-top: 10px;
}
</style>
使用第三方动画库(如 Animate.css)
结合 Animate.css 可以快速实现 SlideDown 效果,减少手写 CSS 的工作量。
<template>
<div>
<button @click="toggle">Toggle Slide</button>
<transition
enter-active-class="animate__animated animate__slideInDown"
leave-active-class="animate__animated animate__slideOutUp"
>
<div v-if="isVisible" class="content">
This content will slide down and up with Animate.css.
</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
isVisible: false
};
},
methods: {
toggle() {
this.isVisible = !this.isVisible;
}
}
};
</script>
<style>
.content {
background: #f0f0f0;
padding: 10px;
margin-top: 10px;
}
</style>
使用动态样式绑定
通过动态绑定 style 或 class,结合 Vue 的响应式数据实现高度变化的动画效果。

<template>
<div>
<button @click="toggle">Toggle Slide</button>
<div
class="content"
:style="{ height: isVisible ? 'auto' : '0' }"
ref="content"
>
This content will slide down and up dynamically.
</div>
</div>
</template>
<script>
export default {
data() {
return {
isVisible: false
};
},
methods: {
toggle() {
this.isVisible = !this.isVisible;
}
}
};
</script>
<style>
.content {
transition: height 0.5s ease;
overflow: hidden;
background: #f0f0f0;
padding: 10px;
margin-top: 10px;
}
</style>
注意事项
- 使用
max-height时需设置足够大的值以确保内容完全展开。 - 动态高度计算可能需要 JavaScript 辅助,如通过
ref获取元素的实际高度。 - 第三方库(如 Animate.css)需提前引入到项目中。
以上方法均能实现 SlideDown 效果,可根据项目需求选择合适的方式。






