vue实现slidetoggle
Vue 实现 SlideToggle 效果
在 Vue 中实现类似 jQuery 的 slideToggle 效果,可以通过 Vue 的过渡系统结合 CSS 动画或 JavaScript 钩子完成。以下是两种常见实现方式:
使用 Vue Transition 和 CSS
Vue 的 <transition> 组件配合 CSS 过渡属性可实现滑动效果:
<template>
<div>
<button @click="toggle">Toggle Slide</button>
<transition name="slide">
<div v-if="isVisible" class="content">可滑动的内容</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; /* 调整为实际内容高度 */
}
</style>
使用动态样式绑定
通过动态计算高度并绑定样式实现更精确的控制:
<template>
<div>
<button @click="toggle">Toggle Slide</button>
<div ref="content" class="content" :style="{ height: currentHeight }">
可滑动的内容
</div>
</div>
</template>
<script>
export default {
data() {
return { isOpen: false, currentHeight: '0px' };
},
methods: {
toggle() {
this.isOpen = !this.isOpen;
this.currentHeight = this.isOpen
? `${this.$refs.content.scrollHeight}px`
: '0px';
}
}
};
</script>
<style>
.content {
overflow: hidden;
transition: height 0.3s ease;
}
</style>
使用第三方库
若需更复杂效果,可引入专门库:
- VueUse 的
useTransition:import { useTransition } from '@vueuse/core'; const height = useTransition(0, { duration: 300 }); - vue-slide-toggle 插件:
<slide-toggle> <div>内容</div> </slide-toggle>
注意事项
- 使用
max-height时需设置足够大的值以容纳内容。 - 动态高度方案需通过
scrollHeight获取实际内容高度。 - 过渡动画的性能可通过
will-change: max-height优化。







