Vue实现可拖拽边界布局
<template>
<div class="container">
<div class="split-pane" ref="splitPane">
<div class="pane" ref="leftPane">左侧内容</div>
<div class="pane" ref="rightPane">右侧内容</div>
<div class="split-bar" ref="splitBar" @mousedown="initDrag"></div>
</div>
</div>
</template>
<script>
export default {
methods: {
initDrag(e) {
e.preventDefault();
document.addEventListener('mousemove', this.doDrag);
document.addEventListener('mouseup', this.stopDrag);
},
doDrag(e) {
const splitPane = this.$refs.splitPane;
const splitBar = this.$refs.splitBar;
const x = e.clientX - splitPane.offsetLeft;
const minWidth = splitBar.offsetWidth;
const maxWidth = splitPane.offsetWidth - minWidth;
const leftWidth = Math.min(maxWidth, Math.max(minWidth, x));
splitBar.style.left = `${leftWidth}px`;
},
stopDrag() {
document.removeEventListener('mousemove', this.doDrag);
document.removeEventListener('mouseup', this.stopDrag);
}
}
}
</script>
<style scoped>
.container {
height: 100vh;
display: flex;
justify-content: center;
align-items: stretch;
}
.split-pane {
width: 100%;
height: 100%;
position: relative;
display: flex;
}
.pane {
flex: 1;
position: relative;
overflow: hidden;
}
.split-bar {
width: 10px;
height: 100%;
cursor: col-resize;
background-color: #ccc;
position: absolute;
left: 50%;
}
</style>
这段代码提供了一个简单的Vue组件,用于实现一个可拖拽分割栏的布局。组件包含三个部分:<template>
定义了布局结构,<script>
中定义了相关的方法来处理拖拽事件,<style>
中定义了一些基本的CSS样式来美化界面。代码使用了mousedown
、mousemove
和mouseup
事件来处理拖拽行为,并限制了分割栏的宽度以保证布局的合理性。
评论已关闭