vue实现slidetoggle
Vue 实现 SlideToggle 效果
在 Vue 中实现类似 jQuery 的 slideToggle 效果,可以通过结合 CSS 过渡和 Vue 的动态绑定来实现。以下是几种常见方法:

使用 Vue Transition 组件
Vue 内置的 <transition> 组件可以方便地实现元素的显示/隐藏过渡效果。

<template>
<div>
<button @click="toggle">Toggle</button>
<transition name="slide">
<div v-show="isVisible" class="content">
Content to be toggled
</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: 500px; /* 设置为足够大的值 */
}
.content {
background: #f0f0f0;
padding: 10px;
}
</style>
使用动态样式绑定
通过动态绑定元素的 style 属性来实现高度变化。
<template>
<div>
<button @click="toggle">Toggle</button>
<div
ref="content"
:style="{ height: isVisible ? contentHeight + 'px' : '0' }"
class="content"
>
Content to be toggled
</div>
</div>
</template>
<script>
export default {
data() {
return {
isVisible: false,
contentHeight: 0
}
},
mounted() {
this.contentHeight = this.$refs.content.scrollHeight
},
methods: {
toggle() {
this.isVisible = !this.isVisible
}
}
}
</script>
<style>
.content {
transition: height 0.3s ease;
overflow: hidden;
background: #f0f0f0;
padding: 10px;
}
</style>
使用第三方库
如果需要更复杂的效果,可以考虑使用专门为 Vue 设计的动画库,如 vue-animate 或 animate.css。
<template>
<div>
<button @click="toggle">Toggle</button>
<transition
enter-active-class="animate__animated animate__slideInDown"
leave-active-class="animate__animated animate__slideOutUp"
>
<div v-show="isVisible" class="content">
Content to be toggled
</div>
</transition>
</div>
</template>
<script>
import 'animate.css'
export default {
data() {
return {
isVisible: false
}
},
methods: {
toggle() {
this.isVisible = !this.isVisible
}
}
}
</script>
注意事项
- 使用
max-height方法时,需要设置一个足够大的值来容纳内容 - 动态计算内容高度时,注意在内容变化后重新计算
- 确保为过渡元素设置了
overflow: hidden属性 - 对于复杂动画,考虑使用 CSS 关键帧动画
以上方法都可以实现类似 jQuery slideToggle 的效果,选择哪种取决于具体需求和项目环境。






