vue3版本的可拖拽宽度的左右布局组件(粗糙版)

247 阅读1分钟
  • html
<template>
	<div id="myBox">
		<div id="silderLeft" :style="{ width: props.width ? props.width + 'px' : '' }">
			<slot name="left"></slot>
		</div>
		<div class="moveBtn" v-move></div>
		<div id="silderRight">
			<slot name="right"></slot>
		</div>
	</div>
</template>
  • script
<script setup lang="ts" name="LayoutSlider">
type Props = {
	width?: number | string;
};

const props = withDefaults(defineProps<Props>(), {
	width: ""
});

const vMove = {
	mounted: el => {
		el.onmousedown = function (e) {
			//清除选中文字
			window.getSelection().empty();
			let init = e.clientX;
			let parent = document.getElementById("silderLeft");
			//外部盒子
			let box = document.getElementById("myBox");
			//右边盒子
			let rightContent = document.getElementById("silderRight");
			let initWidth = parent.offsetWidth;
			let boxWidth = box.offsetWidth;
			//最大拖动宽度
			let maxWidth = parseInt(boxWidth * 0.95);
			document.onmousemove = function (e) {
				window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
				let end = e.clientX;
				let newWidth = end - init + initWidth;
				if (newWidth > 50 && newWidth < maxWidth) {
					parent.style.width = newWidth + "px";
					rightContent.style.width = boxWidth - newWidth + "px";
				} else if (newWidth >= maxWidth) {
					end = maxWidth;
					parent.style.width = maxWidth + "px";
					rightContent.style.width = boxWidth - maxWidth + "px";
				} else {
					end = 250;
					// 最小宽度242
					parent.style.width = 50 + "px";
					rightContent.style.width = boxWidth - 50 + "px";
				}
			};
			document.onmouseup = function () {
				document.onmousemove = document.onmouseup = null;
			};
		};
	}
};
</script>
  • css
#myBox {
	width: 100%;
	/* height: 700px; */
	height: 100%;
	min-height: inherit;
	/* border: 1px solid red; */
	display: flex;
}

#silderLeft {
	width: 260px;
	height: 100%;
	/* background-color: #fff; */
	position: relative;
	/* margin-right: 10px; */
	/* padding-right: 8px; */
	overflow-y: auto;
	background-color: var(--el-fill-color-blank);
	// border: 1px solid var(--el-border-color-light);
	border-radius: 6px;
	box-shadow: 0 0 6px 3px rgb(0 0 0 / 4%);
	&:focus,&:hover{
		box-shadow: 0 0 6px 3px rgb(0 0 0 / 6%);
	}
	// /deep/ .card-l {
	// 	.content {
	// 		padding: 0.8vw 0.8vw 1.3vw 0.8vw
	// 	}
	// }
}

/* 拖动条 */
.moveBtn {
	height: 100%;
	width: 0.8vw;
	/* opacity: 0; */
	border-top: 1px solid #eaeef5;
	/* position: absolute; */
	right: 0px;
	top: 0;
	cursor: col-resize;
	background-color: #fff;
	opacity: 0;
}

.menuList {
	/* background-color: yellowgreen; */
	min-height: inherit;
}

#silderRight {
	height: 100%;
	width: calc(99% - 260px);
	// background-color: #f5f7fa;
	/* flex: 1; */
	& > :deep(*) {
		height:100%;
	}
}

示例 拖动图中示例位置即可改变左右模块的宽度 应用于左部筛选tree文字过长时

image.png