vue 实现左右分栏
实现左右分栏的基本结构
使用Vue实现左右分栏可以通过Flex布局或Grid布局快速完成。以下是一个基于Flex布局的示例代码模板:
<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: 'SplitPanel'
}
</script>
<style scoped>
.split-container {
display: flex;
height: 100vh;
}
.left-panel {
flex: 1;
background: #f5f5f5;
overflow: auto;
}
.right-panel {
flex: 1;
background: #fff;
overflow: auto;
}
</style>
可调整宽度的分栏
如果需要允许用户拖动调整分栏宽度,可以结合拖拽事件实现:

<template>
<div class="resizable-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: 300,
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>
.resizable-container {
display: flex;
height: 100vh;
}
.left-panel {
width: 300px;
background: #f5f5f5;
overflow: auto;
resize: none;
}
.divider {
width: 8px;
background: #ddd;
cursor: col-resize;
}
.right-panel {
flex: 1;
background: #fff;
overflow: auto;
}
</style>
响应式分栏布局
针对移动设备添加响应式设计,当屏幕宽度小于某个值时自动切换为上下布局:
@media (max-width: 768px) {
.split-container {
flex-direction: column;
}
.left-panel, .right-panel {
width: 100% !important;
flex: none;
}
}
使用第三方组件库
对于更复杂的需求,可以考虑使用现成的Vue组件库:

vue-split-panel:专门用于创建可调整的分割面板element-ui的el-container布局组件vuetify的v-container网格系统
安装vue-split-panel的示例:
npm install vue-split-panel
使用示例:
<template>
<split-panel>
<split-panel-item :size="30">
<slot name="left"></slot>
</split-panel-item>
<split-panel-item :size="70">
<slot name="right"></slot>
</split-panel-item>
</split-panel>
</template>
<script>
import { SplitPanel, SplitPanelItem } from 'vue-split-panel'
export default {
components: { SplitPanel, SplitPanelItem }
}
</script>
注意事项
- 分栏高度通常需要明确设置(如
100vh或具体像素值),否则可能无法正常显示 - 内容溢出时建议添加
overflow: auto保证可滚动 - 可拖动分隔条需要处理好鼠标事件,避免与其他交互冲突
- 响应式设计时要考虑不同设备下的用户体验差异






