父组件
<template>
<div
:style="{
'padding-left': moveInfo.width + 'px',
}"
class="drag-class"
>
<div
:style="{
width: moveInfo.width + 'px',
height: moveInfo.height + 'px',
}"
class="content-text"
></div>
<div class="right"></div>
<ChangeWidth
ref="aa"
@widthChange="changeWidth"
@clearEvent="clearEvent"
:left="moveInfo.width"
/>
</div>
</template>
<script>
import ChangeWidth from "./ChangeWidth";
export default {
components: { ChangeWidth },
name: "demo",
data() {
return {
moveInfo: {
width: 400,
height: 100,
},
};
},
methods: {
// 改变drag宽度尺寸
changeWidth(width) {
const newWidth = this.moveInfo.width + width;
this.moveInfo.width = newWidth;
// 设置div的最小宽度和最大宽度
if (this.moveInfo.width <= 200) {
this.moveInfo.width = 200;
this.$refs.aa.mouseUp();
}
if (this.moveInfo.width >= 900) {
this.moveInfo.width = 900;
this.$refs.aa.mouseUp();
}
},
// 清除鼠标事件
clearEvent() {
document.onmousemove = null;
document.onmouseup = null;
},
},
};
</script>
<style lang="less" scoped>
.drag-class {
position: relative;
height: 100%;
.content-text {
position: absolute;
left: 0;
background-color: orange;
}
.right {
margin-left: 5px;
height: 100px;
background-color: skyblue;
}
}
</style>
子组件
<template>
<!-- 拖动右边距改变div宽度 -->
<div
class="x-handle"
@mousedown="mouseDown"
@mouseup="mouseUp"
:style="{ left: left }"
></div>
</template>
<script>
export default {
name: "ChangeWidth",
props: ["left"],
data() {
return {
lastX: 0,
};
},
methods: {
mouseDown(event) {
document.addEventListener("mousemove", this.mouseMove);
this.lastX = event.screenX; // 鼠标指针相对于屏幕的水平坐标
},
mouseMove(e) {
let width = e.screenX - this.lastX;
this.$emit("widthChange", width);
this.lastX = e.screenX;
},
mouseUp() {
this.lastX = 0;
document.removeEventListener("mousemove", this.mouseMove);
this.$emit("clearEvent");
},
},
};
</script>
<style lang="less" scoped>
.x-handle {
width: 5px;
cursor: e-resize;
// background: #2866f0;
height: 100%;
position: absolute;
top: 0;
}
</style>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。