对于一些老项目无法升级ElementUI基础框架且美观和业务相对简单的情况下还是值得推荐尝试的一种方案。如果是新项目推荐直接升级框架的方式最靠谱。官方提供的el-drawer才是最优的选择。
今天在维护vue2框架的一个业务系统遇到这样一个问题,有一个需求需要实现类似于购物车的效果,因为本身框架使用的是ElementUI框架,首先想到的就是使用官方提供的el-drawer。

所以按照官方文档准备在现有系统写一个Demo,写完之后调试了半个小时。始终无法实现抽屉的效果。最后看了下elementui的版本是2.10.1,最后发现这个版本是不支持抽屉组件的。

图片
考虑到属于老项目并且一直运行比较稳定,如果贸然升级elementui基础框架的话风险还是非常大的。最后决定基于ElementUI的Dialog组件自定义的方式来实现抽屉的效果。下面给大家分享具体实现的过程,感兴趣的前端朋友可以看一看!
二、代码介绍
这部分相对比较简单,直接使用Dialog组件的基本结构,然后通过自定义模板实现类似抽屉的标题栏和内容区域。
2.1 CSS部分
这部分是核心,需要定位对话框位置在页面最右侧,并且实现类似于抽屉从右向左滑动的效果。
定位与尺寸
- 使用
position: fixed将Dialog固定到视口右侧 - 设置
height: 100vh实现全高效果 - 通过
right: 0和top: 0定位到右上角 - 去除默认的圆角(
border-radius: 0)和边距(margin: 0)
动画效果
页面初始状态使用transform: translateX(100%)将Dialog对话框隐藏在右侧之外,需要打开对话框的时候通过CSS transition实现平滑的滑入效果。
.drawer-dialog { transform: translateX(100%); transition: transform 0.3s ease-out;}.drawer-dialog.dialog-fade-enter-active { transform: translateX(0);}
.drawer-dialog {
transform: translateX(100%);
transition: transform 0.3s ease-out;
}
.drawer-dialog.dialog-fade-enter-active {
transform: translateX(0);
}
2.2 JS部分
主要是实现抽屉的展示、隐藏逻辑、状态管理、计算抽屉的宽度功能。
2.3 完整的代码示例
<!DOCTYPE html><html lang="zh-CN"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>右侧滑出抽屉组件</title> <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script> <script src="https://unpkg.com/element-ui/lib/index.js"></script> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: 'Helvetica Neue', Arial, sans-serif; background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); min-height: 100vh; display: flex; flex-direction: column; align-items: center; padding: 40px 20px; color: #2c3e50; } .container { max-width: 800px; width: 100%; text-align: center; } h1 { margin-bottom: 20px; font-weight: 500; } .description { margin-bottom: 30px; color: #5e6d82; line-height: 1.6; } .control-panel { background: white; border-radius: 8px; padding: 25px; margin-bottom: 30px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); } .button-group { display: flex; justify-content: center; gap: 15px; margin-bottom: 20px; flex-wrap: wrap; } .demo-content { background: white; border-radius: 8px; padding: 30px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); margin-bottom: 30px; } .demo-content p { margin-bottom: 15px; color: #5e6d82; } .status-info { margin-top: 20px; padding: 12px; background: #f0f9ff; border-radius: 4px; border-left: 4px solid #409EFF; } /* 抽屉组件样式 */ .slide-drawer-mask { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); z-index: 9998; } .slide-drawer { position: fixed; top: 0; right: 0; height: 100%; background: white; box-shadow: -2px 0 12px rgba(0, 0, 0, 0.15); display: flex;
用Dialog实现抽屉效果

最低0.47元/天 解锁文章
3277

被折叠的 条评论
为什么被折叠?



