vue实现侧边抽屉
Vue 实现侧边抽屉
使用 Vue 原生实现
创建一个抽屉组件,通过 v-model 控制显示和隐藏。
<template>
<div class="drawer-container">
<div class="drawer-mask" v-if="isOpen" @click="closeDrawer"></div>
<div class="drawer" :class="{ 'drawer-open': isOpen }">
<slot></slot>
</div>
</div>
</template>
<script>
export default {
props: {
value: {
type: Boolean,
default: false
}
},
computed: {
isOpen: {
get() {
return this.value
},
set(val) {
this.$emit('input', val)
}
}
},
methods: {
closeDrawer() {
this.isOpen = false
}
}
}
</script>
<style>
.drawer-container {
position: relative;
}
.drawer-mask {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
z-index: 999;
}
.drawer {
position: fixed;
top: 0;
left: 0;
width: 300px;
height: 100%;
background-color: #fff;
box-shadow: 2px 0 8px rgba(0, 0, 0, 0.15);
transform: translateX(-100%);
transition: transform 0.3s ease;
z-index: 1000;
}
.drawer-open {
transform: translateX(0);
}
</style>
使用第三方库
Vant、Element UI 等 UI 库提供了现成的抽屉组件。

Vant 示例:
<template>
<van-button type="primary" @click="showDrawer">显示抽屉</van-button>
<van-popup
v-model="show"
position="left"
:style="{ width: '80%', height: '100%' }"
>
抽屉内容
</van-popup>
</template>
<script>
import { Popup, Button } from 'vant'
export default {
components: {
[Popup.name]: Popup,
[Button.name]: Button
},
data() {
return {
show: false
}
},
methods: {
showDrawer() {
this.show = true
}
}
}
</script>
Element UI 示例:

<template>
<el-button @click="drawer = true" type="primary">打开抽屉</el-button>
<el-drawer
title="标题"
:visible.sync="drawer"
direction="ltr"
:before-close="handleClose"
>
<span>内容区域</span>
</el-drawer>
</template>
<script>
export default {
data() {
return {
drawer: false
}
},
methods: {
handleClose(done) {
done()
}
}
}
</script>
动画优化
为抽屉添加平滑的动画效果,可以使用 CSS transition 或 Vue 的 <transition> 组件。
<template>
<transition name="slide">
<div class="drawer" v-if="isOpen">
<slot></slot>
</div>
</transition>
</template>
<style>
.slide-enter-active, .slide-leave-active {
transition: transform 0.3s ease;
}
.slide-enter, .slide-leave-to {
transform: translateX(-100%);
}
</style>
响应式设计
根据屏幕宽度调整抽屉大小。
.drawer {
width: 300px;
}
@media (max-width: 768px) {
.drawer {
width: 80%;
}
}
注意事项
- 确保抽屉的
z-index高于页面其他元素 - 移动端考虑手势滑动关闭功能
- 抽屉内容过长时需要处理滚动问题
- 考虑无障碍访问,添加适当的 ARIA 属性






