vue实现左侧滑出效果
使用 Vue 实现左侧滑出效果
方法一:使用 CSS Transition 和 Vue 数据绑定
通过 Vue 的 v-bind 绑定 class 或 style,结合 CSS 的 transition 实现平滑滑动效果。
<template>
<div>
<button @click="toggleSidebar">Toggle Sidebar</button>
<div class="sidebar" :class="{ 'active': isActive }">
<!-- 侧边栏内容 -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
isActive: false
};
},
methods: {
toggleSidebar() {
this.isActive = !this.isActive;
}
}
};
</script>
<style>
.sidebar {
position: fixed;
left: -250px;
width: 250px;
height: 100vh;
background: #333;
transition: left 0.3s ease;
}
.sidebar.active {
left: 0;
}
</style>
方法二:使用 Vue Transition 组件
利用 Vue 内置的 <transition> 组件实现动画效果,支持更复杂的动画钩子。
<template>
<div>
<button @click="showSidebar = !showSidebar">Toggle Sidebar</button>
<transition name="slide">
<div class="sidebar" v-if="showSidebar">
<!-- 侧边栏内容 -->
</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
showSidebar: false
};
}
};
</script>
<style>
.slide-enter-active, .slide-leave-active {
transition: transform 0.3s ease;
}
.slide-enter, .slide-leave-to {
transform: translateX(-100%);
}
.sidebar {
position: fixed;
left: 0;
width: 250px;
height: 100vh;
background: #333;
}
</style>
方法三:结合第三方库(如 VueUse)
使用 @vueuse/core 的 useTransition 实现更灵活的动画控制。
<template>
<div>
<button @click="toggleSidebar">Toggle Sidebar</button>
<div class="sidebar" :style="{ left: `${left}px` }">
<!-- 侧边栏内容 -->
</div>
</div>
</template>
<script>
import { useTransition } from '@vueuse/core';
export default {
data() {
return {
isActive: false
};
},
setup() {
const left = useTransition(0, {
duration: 300,
transition: [0.25, 0.1, 0.25, 1] // 缓动函数
});
return { left };
},
methods: {
toggleSidebar() {
this.isActive = !this.isActive;
this.left = this.isActive ? 0 : -250;
}
}
};
</script>
<style>
.sidebar {
position: fixed;
width: 250px;
height: 100vh;
background: #333;
}
</style>
方法四:响应式适配移动端
添加触摸事件支持,优化移动端体验。

<template>
<div>
<div
class="sidebar"
:class="{ 'active': isActive }"
@touchstart="startDrag"
@touchmove="onDrag"
@touchend="endDrag"
>
<!-- 侧边栏内容 -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
isActive: false,
startX: 0,
currentX: 0
};
},
methods: {
startDrag(e) {
this.startX = e.touches[0].clientX;
},
onDrag(e) {
this.currentX = e.touches[0].clientX - this.startX;
if (this.currentX > 0) {
this.currentX = 0;
}
},
endDrag() {
if (this.currentX < -50) {
this.isActive = false;
} else {
this.isActive = true;
}
this.currentX = 0;
}
}
};
</script>
<style>
.sidebar {
position: fixed;
left: -250px;
width: 250px;
height: 100vh;
background: #333;
transition: transform 0.3s ease;
}
.sidebar.active {
transform: translateX(250px);
}
</style>
注意事项
- 性能优化:避免在动画中使用
left属性,优先使用transform。 - 遮罩层:可添加半透明遮罩层增强用户体验。
- 浏览器兼容性:测试不同浏览器的
transition和transform支持情况。






