vue 实现左右分栏
实现左右分栏的基本结构
使用 Vue 实现左右分栏布局,可以通过 Flexbox 或 Grid 布局结合组件拆分完成。以下是一个基于 Flexbox 的示例:
<template>
<div class="split-container">
<div class="left-panel">
<!-- 左侧内容 -->
<slot name="left"></slot>
</div>
<div class="right-panel">
<!-- 右侧内容 -->
<slot name="right"></slot>
</div>
</div>
</template>
<script>
export default {
name: 'SplitLayout'
}
</script>
<style scoped>
.split-container {
display: flex;
height: 100vh;
}
.left-panel {
flex: 1;
background: #f0f0f0;
}
.right-panel {
flex: 1;
background: #e0e0e0;
}
</style>
添加可调整的分栏宽度
通过拖动分隔线调整左右分栏宽度,需监听鼠标事件:
<template>
<div class="split-container">
<div class="left-panel" :style="{ width: leftWidth + 'px' }">
<slot name="left"></slot>
</div>
<div class="divider" @mousedown="startDrag"></div>
<div class="right-panel">
<slot name="right"></slot>
</div>
</div>
</template>
<script>
export default {
data() {
return {
leftWidth: 200,
isDragging: false
}
},
methods: {
startDrag(e) {
this.isDragging = true
document.addEventListener('mousemove', this.onDrag)
document.addEventListener('mouseup', this.stopDrag)
},
onDrag(e) {
if (this.isDragging) {
this.leftWidth = e.clientX
}
},
stopDrag() {
this.isDragging = false
document.removeEventListener('mousemove', this.onDrag)
document.removeEventListener('mouseup', this.stopDrag)
}
}
}
</script>
<style scoped>
.split-container {
display: flex;
height: 100vh;
}
.left-panel {
background: #f0f0f0;
}
.right-panel {
flex: 1;
background: #e0e0e0;
}
.divider {
width: 5px;
background: #ccc;
cursor: col-resize;
}
</style>
响应式分栏布局
添加媒体查询实现移动端适配:

@media (max-width: 768px) {
.split-container {
flex-direction: column;
}
.left-panel, .right-panel {
width: 100% !important;
}
.divider {
width: 100%;
height: 5px;
cursor: row-resize;
}
}
使用第三方库
若需更复杂功能(如嵌套分栏),可考虑以下库:
vue-splitpane:提供预构建的分栏组件split.js:轻量级的分栏控制库
安装 vue-splitpane 的示例:

npm install vue-splitpane
使用方式:
<template>
<split-pane :min-percent="20" :default-percent="30" split="vertical">
<template #paneL>左侧内容</template>
<template #paneR>右侧内容</template>
</split-pane>
</template>
<script>
import SplitPane from 'vue-splitpane'
export default {
components: { SplitPane }
}
</script>
性能优化建议
对于内容复杂的分栏:
- 使用
v-if或keep-alive控制子组件渲染 - 对静态内容使用
v-once指令 - 避免在分栏内使用重型计算属性






