二次封装element plus抽屉
时间: 2025-01-29 22:05:39 浏览: 40
### 封装 Element Plus 的 `el-drawer` 组件
为了增强功能并简化使用,可以创建一个新的 Vue 组件来封装原生的 `el-drawer` 组件。此新组件不仅继承了原始组件的功能,还增加了额外特性如快捷键支持、动态调整尺寸等功能。
#### 创建基础结构
首先,在项目中新建一个名为 `CustomDrawer.vue` 文件用于定义新的抽屉组件:
```vue
<template>
<div class="custom-drawer">
<!-- 使用 element-plus 提供的基础 drawer -->
<el-drawer v-bind="$attrs" :visible.sync="drawerVisible" @close="handleClose()">
<slot></slot> <!-- 插槽允许传递任意内容到内部 -->
</el-drawer>
</div>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue';
const props = defineProps({
modelValue: Boolean,
});
// 双向绑定 visible 属性以便外部控制显示状态
const emit = defineEmits(['update:modelValue']);
let drawerVisible = ref(props.modelValue);
watch(() => props.modelValue, (newValue) => {
drawerVisible.value = newValue;
}, { immediate: true });
function handleClose() {
emit('update:modelValue', false);
}
</script>
<style scoped>
.custom-drawer {}
</style>
```
上述代码实现了最基本的双向数据绑定机制[^1],使得父级可以通过 `v-model` 来管理当前实例的状态变化。
#### 添加快捷键处理逻辑
为了让用户体验更佳,可以在该组件内监听全局键盘事件从而响应特定组合键的操作:
```javascript
mounted() {
document.addEventListener('keydown', this.handleKeyDown);
},
beforeDestroy() {
document.removeEventListener('keydown', this.handleKeyDown); // 清除事件监听器防止内存泄漏
},
methods: {
handleKeyDown(event) {
const keyMap = {
Escape: () => this.close(),
ArrowUp: () => console.log('上一页'),
ArrowDown: () => console.log('下一页'),
ArrowLeft: () => console.log('打开第一个条目'),
ArrowRight: () => this.close()
};
if (!this.drawerVisible || !event.shiftKey) return;
let action = keyMap[event.key];
if (action) action();
},
close() {
this.$emit('update:modelValue', false);
}
}
```
这段脚本通过监听文档级别的按键按下事件(`keydown`),当检测到指定方向键加上 Shift 键被按下的时候执行相应的方法调用[^3]。
#### 实现窗口大小调节能力
对于希望提供更加灵活布局的应用程序来说,能够自由调整侧边栏宽度是非常有用的。为此,可在样式表里加入一些 CSS 类名,并利用 JavaScript 动态修改这些类对应的属性值达到目的:
```css
.resizable-handle {
position: absolute;
top: 0;
bottom: 0;
width: 8px;
background-color: rgba(0, 0, 0, .2);
cursor: ew-resize;
}
/* 更多样式可以根据实际需求定制 */
```
接着更新模板部分以包含手柄元素以及相应的交互行为:
```html
<div class="resizable-handle" @mousedown.prevent.stop="startResize"></div>
<!-- ...其他原有代码保持不变 -->
<script>
data() {
return {
startX: null,
startWidth: null
};
},
methods: {
startResize(e) {
this.startX = e.clientX;
this.startWidth = parseInt(window.getComputedStyle(this.$refs.container).width.slice(0,-2));
window.addEventListener('mousemove', this.onMouseMove);
window.addEventListener('mouseup', this.endResize);
},
onMouseMove(e){
var dx = e.clientX - this.startX;
this.$refs.container.style.width = `${this.startWidth + dx}px`;
},
endResize(){
window.removeEventListener('mousemove', this.onMouseMove);
window.removeEventListener('mouseup', this.endResize);
}
}
</script>
```
以上就是关于如何对 Element Plus 中的 `el-drawer` 进行二次开发的一些思路和技术细节介绍[^2]。
阅读全文
相关推荐
















