vue实现slidetoggle
Vue 实现 SlideToggle 效果
SlideToggle 是一种常见的交互效果,元素以滑动方式展开或收起。以下是几种实现方法:

使用 CSS Transition 和 v-show
通过 Vue 的 v-show 指令和 CSS 过渡实现基础滑动效果。

<template>
<div>
<button @click="toggle">Toggle</button>
<div
class="slide-content"
v-show="isVisible"
:style="{ maxHeight: isVisible ? '500px' : '0' }"
>
Content to slide toggle
</div>
</div>
</template>
<script>
export default {
data() {
return {
isVisible: false
}
},
methods: {
toggle() {
this.isVisible = !this.isVisible
}
}
}
</script>
<style>
.slide-content {
overflow: hidden;
transition: max-height 0.3s ease;
}
</style>
使用 Vue Transition 组件
Vue 内置的 <transition> 组件可以更灵活地控制动画效果。
<template>
<div>
<button @click="toggle">Toggle</button>
<transition name="slide">
<div class="content" v-show="isVisible">
Slide content here
</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.3s ease;
overflow: hidden;
}
.slide-enter-from, .slide-leave-to {
max-height: 0;
}
.slide-enter-to, .slide-leave-from {
max-height: 500px;
}
</style>
使用第三方库(如 VueUse)
VueUse 提供了 useTransition 工具函数,可以更精细地控制过渡效果。
<template>
<div>
<button @click="toggle">Toggle</button>
<div
class="slide-content"
:style="{ height: `${height}px` }"
>
Content to slide toggle
</div>
</div>
</template>
<script>
import { ref } from 'vue'
import { useTransition } from '@vueuse/core'
export default {
setup() {
const isVisible = ref(false)
const contentRef = ref(null)
const height = useTransition(
isVisible,
{
duration: 300,
transition: [0.25, 0.1, 0.25, 1]
}
)
const toggle = () => {
isVisible.value = !isVisible.value
}
return { height, toggle }
}
}
</script>
<style>
.slide-content {
overflow: hidden;
}
</style>
注意事项
- 确保为滑动元素设置
overflow: hidden属性 - 滑动高度应根据实际内容动态计算,避免硬编码
- 移动端设备可能需要额外考虑性能优化
- 复杂动画场景建议使用 CSS 硬件加速属性如
transform






