vue实现slidedown
Vue 实现 SlideDown 效果
SlideDown 是一种常见的动画效果,用于平滑地展开元素。在 Vue 中可以通过多种方式实现,以下是几种常见的方法:
使用 CSS Transition 实现
通过 Vue 的 v-if 或 v-show 控制元素的显示与隐藏,结合 CSS Transition 实现动画效果。

<template>
<div>
<button @click="toggle">Toggle Slide</button>
<transition name="slide">
<div v-show="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, .slide-leave-to {
max-height: 0;
}
.slide-enter-to, .slide-leave {
max-height: 1000px;
}
.content {
background: #f0f0f0;
padding: 10px;
}
</style>
使用 Vue Transition 钩子
通过 JavaScript 钩子函数实现更复杂的动画控制。

<template>
<div>
<button @click="toggle">Toggle Slide</button>
<transition
@before-enter="beforeEnter"
@enter="enter"
@leave="leave"
>
<div v-show="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;
},
beforeEnter(el) {
el.style.height = '0';
},
enter(el) {
el.style.height = `${el.scrollHeight}px`;
},
leave(el) {
el.style.height = '0';
}
}
};
</script>
<style>
.content {
transition: height 0.5s ease;
overflow: hidden;
background: #f0f0f0;
padding: 10px;
}
</style>
使用第三方库(如 VueUse)
利用 @vueuse/core 提供的 useTransition 实现更平滑的动画效果。
<template>
<div>
<button @click="toggle">Toggle Slide</button>
<div ref="content" class="content">
This content will slide down and up.
</div>
</div>
</template>
<script>
import { ref } from 'vue';
import { useTransition } from '@vueuse/core';
export default {
setup() {
const content = ref(null);
const isVisible = ref(false);
const height = useTransition(
() => (isVisible.value ? content.value.scrollHeight : 0),
{ duration: 500 }
);
const toggle = () => {
isVisible.value = !isVisible.value;
};
return { content, height, toggle };
}
};
</script>
<style>
.content {
overflow: hidden;
background: #f0f0f0;
padding: 10px;
}
</style>
使用 Tailwind CSS 实现
如果项目中使用了 Tailwind CSS,可以结合其 Transition 类快速实现 SlideDown 效果。
<template>
<div>
<button @click="toggle" class="bg-blue-500 text-white p-2 rounded">
Toggle Slide
</button>
<div
class="overflow-hidden transition-all duration-500 ease-in-out"
:style="{ maxHeight: isVisible ? '1000px' : '0' }"
>
<div class="bg-gray-100 p-4">
This content will slide down and up.
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
isVisible: false
};
},
methods: {
toggle() {
this.isVisible = !this.isVisible;
}
}
};
</script>
以上方法均可实现 SlideDown 效果,选择适合项目需求和技术栈的方案即可。






