使用vue和element-ui实现:一个宽高都是400px的弹窗,可以四个角和边框都能放大和缩小,可以拖拽,只能点x号关闭
时间: 2024-02-17 15:02:50 浏览: 218
好的,我明白了。您可以参考以下的代码实现:
```vue
<template>
<div class="dialog-container" :style="dialogStyles">
<div class="dialog-header" @mousedown="startDrag">
<span class="title">{{ title }}</span>
<i class="el-icon-close close-btn" @click="close"></i>
</div>
<div class="dialog-body">
<slot></slot>
</div>
<div class="dialog-resize" @mousedown="startResize"></div>
</div>
</template>
<script>
export default {
name: 'ResizableDialog',
props: {
title: {
type: String,
default: ''
},
width: {
type: [String, Number],
default: 400
},
height: {
type: [String, Number],
default: 400
}
},
data() {
return {
isDragging: false,
isResizing: false,
initMouseX: 0,
initMouseY: 0,
initWidth: 0,
initHeight: 0
}
},
computed: {
dialogStyles() {
return {
width: `${this.width}px`,
height: `${this.height}px`
}
}
},
methods: {
startDrag(e) {
this.isDragging = true;
this.initMouseX = e.clientX;
this.initMouseY = e.clientY;
this.initWidth = this.width;
this.initHeight = this.height;
document.addEventListener('mousemove', this.drag);
document.addEventListener('mouseup', this.stopDrag);
},
drag(e) {
if (this.isDragging) {
const dx = e.clientX - this.initMouseX;
const dy = e.clientY - this.initMouseY;
this.width = this.initWidth + dx;
this.height = this.initHeight + dy;
}
},
stopDrag() {
this.isDragging = false;
document.removeEventListener('mousemove', this.drag);
document.removeEventListener('mouseup', this.stopDrag);
},
startResize(e) {
this.isResizing = true;
this.initMouseX = e.clientX;
this.initMouseY = e.clientY;
this.initWidth = this.width;
this.initHeight = this.height;
document.addEventListener('mousemove', this.resize);
document.addEventListener('mouseup', this.stopResize);
},
resize(e) {
if (this.isResizing) {
const dx = e.clientX - this.initMouseX;
const dy = e.clientY - this.initMouseY;
this.width = this.initWidth + dx;
this.height = this.initHeight + dy;
}
},
stopResize() {
this.isResizing = false;
document.removeEventListener('mousemove', this.resize);
document.removeEventListener('mouseup', this.stopResize);
},
close() {
this.$emit('update:visible', false);
}
}
}
</script>
<style scoped>
.dialog-container {
position: absolute;
border: 1px solid #ccc;
background-color: #fff;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
z-index: 1000;
}
.dialog-header {
padding: 10px;
background-color: #f5f7fa;
border-bottom: 1px solid #d1dbe5;
cursor: move;
}
.dialog-header .title {
font-weight: bold;
}
.dialog-header .close-btn {
float: right;
cursor: pointer;
}
.dialog-body {
padding: 10px;
}
.dialog-resize {
position: absolute;
bottom: 0;
right: 0;
width: 10px;
height: 10px;
cursor: se-resize;
z-index: 1000;
}
</style>
```
上面的代码实现了一个宽高都是400px的弹窗,可以拖拽,四个角和边框都能放大和缩小,只能点击关闭按钮来关闭弹窗。需要注意的是,由于需要监听鼠标事件,所以需要在 mounted 钩子中将 document 的事件监听器添加进去,并在 beforeDestroy 钩子中将其移除。另外,由于需要在父组件中控制弹窗的显示和隐藏,所以使用了 `visible` 这个 prop 作为控制变量,当点击关闭按钮时,通过 `$emit` 发送 `update:visible` 事件来通知父组件更新 `visible` 的值。
阅读全文