<template>
<div class="box" :style="{width: width + 'px', height: height + 'px'}">
<!-- 宽度控件 -->
<div class="width-control" :style="{left: width - 10 + 'px'}" @mousedown.prevent="startDragWidth"></div>
<!-- 高度控件 -->
<div class="height-control" :style="{top: height - 10 + 'px'}" @mousedown.prevent="startDragHeight"></div>
</div>
</template>
<script>
export default {
data() {
return {
// 盒子宽度和高度
width: 200,
height: 200,
// 拖拽相关参数
isDraggingWidth: false,
isDraggingHeight: false,
startX: 0,
startY: 0
}
},
methods: {
startDragWidth(e) {
this.isDraggingWidth = true;
this.startX = e.clientX;
},
startDragHeight(e) {
this.isDraggingHeight = true;
this.startY = e.clientY;
},
endDrag() {
this.isDraggingWidth = false;
this.isDraggingHeight = false;
},
handleMouseMove(e) {
if (this.isDraggingWidth) {
const dx = e.clientX - this.startX;
this.width += dx;
this.startX = e.clientX;
} else if (this.isDraggingHeight) {
const dy = e.clientY - this.startY;
this.height += dy;
this.startY = e.clientY;
}
}
},
mounted() {
document.addEventListener('mousemove', this.handleMouseMove);
document.addEventListener('mouseup', this.endDrag);
},
beforeDestroy() {
document.removeEventListener('mousemove', this.handleMouseMove);
document.removeEventListener('mouseup', this.endDrag);
}
}
</script>
<style scoped>
.box {
position: relative;
border: 1px solid #ccc;
}
.width-control, .height-control {
position: absolute;
width: 10px;
height: 10px;
background-color: #f00;
cursor: pointer;
}
.width-control {
top: 50%;
transform: translate(-50%, -50%);
}
.height-control {
left: 50%;
transform: translate(-50%, -50%);
}
</style>
这个组件中,我使用了两个 div
元素作为宽度和高度控件,并用样式将它们定位到了盒子的右边和底部。当鼠标按下时,我们通过 @mousedown.prevent="startDragWidth"
或 @mousedown.prevent="startDragHeight"
监听鼠标事件,并设置相应的拖拽状态。在拖拽过程中,我们监听 document
的 mousemove
事件,并根据鼠标移动的距离调整盒子的宽度或高度。最后,在鼠标松开时,我们重置拖拽状态。