vue实现抽屉组件
实现抽屉组件的基本思路
抽屉组件通常用于从屏幕边缘滑出的交互式面板,常见于移动端或后台管理系统。Vue中可以通过动态CSS和过渡动画实现这一效果。
基础HTML结构
<template>
<div class="drawer-container">
<div class="drawer-mask" v-if="visible" @click="close"></div>
<transition name="slide">
<div class="drawer" v-if="visible">
<slot></slot>
</div>
</transition>
</div>
</template>
核心CSS样式
.drawer-container {
position: relative;
}
.drawer-mask {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.5);
z-index: 999;
}
.drawer {
position: fixed;
width: 300px;
height: 100%;
background: #fff;
z-index: 1000;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}
/* 右侧滑入动画 */
.slide-enter-active, .slide-leave-active {
transition: transform 0.3s ease;
}
.slide-enter, .slide-leave-to {
transform: translateX(100%);
}
Vue组件逻辑
<script>
export default {
props: {
visible: {
type: Boolean,
default: false
},
position: {
type: String,
default: 'right' // 支持left/right/top/bottom
}
},
methods: {
close() {
this.$emit('update:visible', false);
}
},
watch: {
visible(newVal) {
if (newVal) {
document.body.style.overflow = 'hidden';
} else {
document.body.style.overflow = '';
}
}
}
};
</script>
使用示例
<template>
<div>
<button @click="showDrawer = true">打开抽屉</button>
<Drawer v-model:visible="showDrawer">
<h3>抽屉内容</h3>
<p>这里可以放置任意内容</p>
</Drawer>
</div>
</template>
<script>
import Drawer from './Drawer.vue';
export default {
components: { Drawer },
data() {
return {
showDrawer: false
};
}
};
</script>
进阶功能扩展
支持不同方向的抽屉效果,可以通过动态绑定CSS类实现:
computed: {
drawerClass() {
return `drawer-${this.position}`;
}
}
.drawer-left {
left: 0;
top: 0;
}
.drawer-right {
right: 0;
top: 0;
}
.drawer-top {
top: 0;
left: 0;
width: 100%;
height: auto;
}
.drawer-bottom {
bottom: 0;
left: 0;
width: 100%;
height: auto;
}
注意事项
- 抽屉组件通常需要处理滚动锁定,防止背景内容滚动
- 移动端需要考虑触摸事件处理
- 可以添加ESC键关闭功能
- 考虑添加自定义宽度/高度属性
- 动画效果可以根据实际需求调整缓动函数







