vue实现侧边栏拖动
实现侧边栏拖动的核心思路
通过监听鼠标事件(mousedown、mousemove、mouseup)计算拖动距离,动态调整侧边栏宽度。需结合 Vue 的响应式数据管理和样式绑定。
基础代码结构
<template>
<div class="container">
<div
class="sidebar"
:style="{ width: sidebarWidth + 'px' }"
>
<!-- 侧边栏内容 -->
</div>
<div
class="drag-handle"
@mousedown="startDrag"
></div>
<div class="main-content">
<!-- 主内容区 -->
</div>
</div>
</template>
实现拖动逻辑
<script>
export default {
data() {
return {
sidebarWidth: 200,
isDragging: false,
startX: 0,
startWidth: 0
}
},
methods: {
startDrag(e) {
this.isDragging = true;
this.startX = e.clientX;
this.startWidth = this.sidebarWidth;
document.addEventListener('mousemove', this.handleDrag);
document.addEventListener('mouseup', this.stopDrag);
},
handleDrag(e) {
if (!this.isDragging) return;
const deltaX = e.clientX - this.startX;
this.sidebarWidth = Math.max(100, this.startWidth + deltaX); // 限制最小宽度
},
stopDrag() {
this.isDragging = false;
document.removeEventListener('mousemove', this.handleDrag);
document.removeEventListener('mouseup', this.stopDrag);
}
}
}
</script>
样式关键点
<style>
.container {
display: flex;
height: 100vh;
}
.sidebar {
background: #f0f0f0;
transition: width 0.2s; /* 可选:添加动画效果 */
}
.drag-handle {
width: 5px;
background: #ddd;
cursor: col-resize;
}
.drag-handle:hover {
background: #ccc;
}
.main-content {
flex: 1;
}
</style>
优化方向
- 边界处理:增加最大宽度限制
Math.min(newWidth, 500) - 触摸屏支持:添加
touchstart、touchmove事件处理 - 持久化:通过
localStorage保存用户调整后的宽度 - 性能优化:使用
requestAnimationFrame替代直接事件处理
完整示例扩展
// 持久化存储
mounted() {
const savedWidth = localStorage.getItem('sidebarWidth');
if (savedWidth) this.sidebarWidth = parseInt(savedWidth);
},
watch: {
sidebarWidth(newVal) {
localStorage.setItem('sidebarWidth', newVal);
}
}
通过组合这些方法,可以实现一个可拖动、可记忆用户设置的侧边栏组件。实际应用中可根据需求调整细节参数。







