vue 实现左右分栏
实现左右分栏的基本结构
使用Vue实现左右分栏可以通过Flex布局或Grid布局快速完成。以下是一个基于Flex布局的示例:
<template>
<div class="container">
<div class="left-sidebar">
<!-- 左侧内容 -->
</div>
<div class="right-content">
<!-- 右侧内容 -->
</div>
</div>
</template>
<style scoped>
.container {
display: flex;
height: 100vh;
}
.left-sidebar {
width: 200px;
background: #f0f0f0;
}
.right-content {
flex: 1;
background: #fff;
}
</style>
可调整宽度的分栏
如果需要实现可拖拽调整宽度的分栏,可以结合鼠标事件:
<template>
<div class="resizable-container">
<div
class="left-panel"
:style="{ width: leftWidth + 'px' }"
>
Left Panel
</div>
<div
class="divider"
@mousedown="startResize"
></div>
<div class="right-panel">
Right Panel
</div>
</div>
</template>
<script>
export default {
data() {
return {
leftWidth: 200,
isResizing: false
}
},
methods: {
startResize(e) {
this.isResizing = true
document.addEventListener('mousemove', this.resize)
document.addEventListener('mouseup', this.stopResize)
},
resize(e) {
if (this.isResizing) {
this.leftWidth = e.clientX
}
},
stopResize() {
this.isResizing = false
document.removeEventListener('mousemove', this.resize)
}
}
}
</script>
<style scoped>
.resizable-container {
display: flex;
height: 100vh;
}
.left-panel {
background: #f5f5f5;
}
.divider {
width: 5px;
background: #ddd;
cursor: col-resize;
}
.right-panel {
flex: 1;
background: #fff;
}
</style>
使用第三方组件
对于更复杂的需求,可以考虑使用专门的分栏组件库:

-
安装
splitpanes组件:npm install splitpanes -
基本使用示例:

<template> <splitpanes> <pane min-size="20"> Left </pane> <pane> Right </pane> </splitpanes> </template>
export default { components: { Splitpanes, Pane } }
```响应式分栏布局
针对不同屏幕尺寸调整分栏行为:
@media (max-width: 768px) {
.container {
flex-direction: column;
}
.left-sidebar {
width: 100%;
height: 100px;
}
}
注意事项
- 分栏高度通常需要设置为100vh或继承父容器高度
- 可拖拽分栏需要处理鼠标事件清理,避免内存泄漏
- 移动端设备可能需要特殊处理拖拽交互
- 考虑添加最小宽度限制,防止面板过小无法操作






