vue 实现jqslidedown
在 Vue 中实现类似 jQuery 的 slideDown 动画效果,可以通过 Vue 的过渡系统或 CSS 动画结合动态样式绑定来完成。以下是几种实现方法:
使用 Vue Transition 组件
Vue 的 <transition> 组件可以方便地实现元素显示/隐藏时的动画效果。结合 CSS 过渡属性,可以模拟 slideDown 效果。
<template>
<div>
<button @click="toggle">Toggle Slide</button>
<transition name="slide">
<div v-if="isVisible" class="content">Content to slide down</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>
使用动态样式绑定
通过动态计算元素的高度并绑定样式,可以实现更精确的滑动效果。
<template>
<div>
<button @click="toggle">Toggle Slide</button>
<div ref="content" :style="{ height: currentHeight + 'px' }" class="content">
Content to slide down
</div>
</div>
</template>
<script>
export default {
data() {
return {
isVisible: false,
currentHeight: 0
};
},
methods: {
toggle() {
this.isVisible = !this.isVisible;
if (this.isVisible) {
this.slideDown();
} else {
this.slideUp();
}
},
slideDown() {
const content = this.$refs.content;
const fullHeight = content.scrollHeight;
let height = 0;
const animate = () => {
height += 10;
this.currentHeight = height;
if (height < fullHeight) {
requestAnimationFrame(animate);
}
};
animate();
},
slideUp() {
let height = this.currentHeight;
const animate = () => {
height -= 10;
this.currentHeight = height;
if (height > 0) {
requestAnimationFrame(animate);
}
};
animate();
}
}
};
</script>
<style>
.content {
overflow: hidden;
transition: height 0.5s ease;
background: #f0f0f0;
padding: 10px;
}
</style>
使用第三方库
如果需要更复杂的动画效果,可以引入第三方动画库如 animate.css 或 Velocity.js。

<template>
<div>
<button @click="toggle">Toggle Slide</button>
<transition
@enter="enter"
@leave="leave"
>
<div v-if="isVisible" class="content">Content to slide down</div>
</transition>
</div>
</template>
<script>
import Velocity from 'velocity-animate';
export default {
data() {
return {
isVisible: false
};
},
methods: {
toggle() {
this.isVisible = !this.isVisible;
},
enter(el, done) {
Velocity(el, { height: [el.scrollHeight, 0] }, { duration: 500, complete: done });
},
leave(el, done) {
Velocity(el, { height: [0, el.scrollHeight] }, { duration: 500, complete: done });
}
}
};
</script>
<style>
.content {
overflow: hidden;
background: #f0f0f0;
padding: 10px;
}
</style>
注意事项
- 使用
max-height过渡时,确保设置的值足够大以容纳内容。 - 动态计算高度时,注意性能问题,避免频繁触发重排。
- 第三方库可以提供更丰富的动画效果,但会增加项目体积。
以上方法均可在 Vue 中实现类似 jQuery 的 slideDown 效果,根据项目需求选择合适的方式。






