vue 实现jqslidedown
在 Vue 中实现类似 jQuery 的 slideDown 效果,可以通过 Vue 的过渡系统结合 CSS 或 JavaScript 动画来实现。以下是几种实现方法:
使用 Vue Transition 和 CSS
Vue 的 <transition> 组件配合 CSS 过渡可以模拟 slideDown 效果。
<template>
<div>
<button @click="show = !show">Toggle Slide</button>
<transition name="slide">
<div v-if="show" class="content">
This content will slide down and up.
</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
show: false
}
}
}
</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; /* Adjust based on content height */
}
.content {
background: #f0f0f0;
padding: 10px;
}
</style>
使用 JavaScript 钩子实现动态高度
如果需要更精确控制高度,可以使用 JavaScript 钩子动态计算内容高度。
<template>
<div>
<button @click="toggleSlide">Toggle Slide</button>
<transition
@enter="enter"
@leave="leave"
:css="false"
>
<div v-if="show" class="content" ref="content">
This content will slide down and up with dynamic height.
</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
show: false
}
},
methods: {
toggleSlide() {
this.show = !this.show;
},
enter(el, done) {
el.style.height = 'auto';
const height = el.clientHeight;
el.style.height = '0';
setTimeout(() => {
el.style.height = `${height}px`;
el.addEventListener('transitionend', done);
}, 0);
},
leave(el, done) {
el.style.height = '0';
el.addEventListener('transitionend', done);
}
}
}
</script>
<style>
.content {
transition: height 0.5s ease;
overflow: hidden;
background: #f0f0f0;
padding: 10px;
}
</style>
使用第三方库
如果需要更复杂的效果,可以集成第三方动画库如 Velocity.js 或 GSAP。
<template>
<div>
<button @click="show = !show">Toggle Slide</button>
<transition
@enter="enter"
@leave="leave"
:css="false"
>
<div v-if="show" class="content">
Content with Velocity.js animation.
</div>
</transition>
</div>
</template>
<script>
import Velocity from 'velocity-animate';
export default {
data() {
return {
show: false
}
},
methods: {
enter(el, done) {
Velocity(el, { height: [el.scrollHeight, 0] }, { duration: 500, complete: done });
},
leave(el, done) {
Velocity(el, { height: 0 }, { duration: 500, complete: done });
}
}
}
</script>
<style>
.content {
overflow: hidden;
background: #f0f0f0;
padding: 10px;
}
</style>
注意事项
- 使用 CSS 方法时,
max-height需要设置为足够大的值以容纳内容,但过渡效果可能不够精确。 - JavaScript 方法可以精确计算高度,但需要处理动态内容高度变化的情况。
- 第三方库提供更丰富的动画效果,但会增加项目体积。







