vue实现下滑效果
Vue 实现下滑效果的方法
使用 CSS 过渡动画
在 Vue 中可以通过 CSS 的 transition 或 @keyframes 实现下滑效果。定义一个下滑的 CSS 类,并通过 Vue 的 v-if 或 v-show 控制元素的显示与隐藏。
<template>
<div>
<button @click="toggleSlide">Toggle Slide</button>
<div class="slide-content" :class="{ 'slide-down': isVisible }">
Content to slide down
</div>
</div>
</template>
<script>
export default {
data() {
return {
isVisible: false,
};
},
methods: {
toggleSlide() {
this.isVisible = !this.isVisible;
},
},
};
</script>
<style>
.slide-content {
max-height: 0;
overflow: hidden;
transition: max-height 0.5s ease-out;
}
.slide-down {
max-height: 500px; /* Adjust based on content height */
}
</style>
使用 Vue Transition 组件
Vue 提供了 <transition> 组件,可以更方便地实现动画效果。结合 CSS 定义进入和离开的动画。
<template>
<div>
<button @click="toggleSlide">Toggle Slide</button>
<transition name="slide">
<div v-if="isVisible" class="slide-content">
Content to slide down
</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
isVisible: false,
};
},
methods: {
toggleSlide() {
this.isVisible = !this.isVisible;
},
},
};
</script>
<style>
.slide-enter-active, .slide-leave-active {
transition: max-height 0.5s ease;
}
.slide-enter, .slide-leave-to {
max-height: 0;
overflow: hidden;
}
.slide-enter-to, .slide-leave {
max-height: 500px; /* Adjust based on content height */
}
</style>
使用第三方库(如 VueUse)
VueUse 提供了 useTransition 或动画相关的工具函数,可以更灵活地实现下滑效果。
<template>
<div>
<button @click="toggleSlide">Toggle Slide</button>
<div :style="{ height: `${height}px` }" class="slide-content">
Content to slide down
</div>
</div>
</template>
<script>
import { ref } from 'vue';
import { useTransition } from '@vueuse/core';
export default {
setup() {
const isVisible = ref(false);
const height = useTransition(isVisible, {
duration: 500,
transition: [0.75, 0, 0.25, 1],
});
const toggleSlide = () => {
isVisible.value = !isVisible.value;
};
return {
height: isVisible.value ? 500 : 0,
toggleSlide,
};
},
};
</script>
<style>
.slide-content {
overflow: hidden;
}
</style>
结合 JavaScript 动画库(如 GSAP)
如果需要更复杂的动画效果,可以结合 GSAP 实现下滑动画。

<template>
<div>
<button @click="toggleSlide">Toggle Slide</button>
<div ref="slideContent" class="slide-content">
Content to slide down
</div>
</div>
</template>
<script>
import { ref } from 'vue';
import gsap from 'gsap';
export default {
setup() {
const slideContent = ref(null);
const isVisible = ref(false);
const toggleSlide = () => {
isVisible.value = !isVisible.value;
if (isVisible.value) {
gsap.to(slideContent.value, {
height: 'auto',
duration: 0.5,
ease: 'power2.out',
});
} else {
gsap.to(slideContent.value, {
height: 0,
duration: 0.5,
ease: 'power2.in',
});
}
};
return {
slideContent,
toggleSlide,
};
},
};
</script>
<style>
.slide-content {
height: 0;
overflow: hidden;
}
</style>
注意事项
- 确保为滑动内容设置
overflow: hidden,避免内容溢出影响动画效果。 - 调整
max-height或height的值为内容实际高度,避免动画不流畅。 - 使用
transition或动画库时,注意性能优化,避免频繁触发重排或重绘。






