当前位置:首页 > VUE

vue实现侧边栏拖动

2026-02-21 17:45:21VUE

vue实现侧边栏拖动

vue实现侧边栏拖动

实现侧边栏拖动的核心思路

通过监听鼠标事件(mousedownmousemovemouseup)计算拖动距离,动态调整侧边栏宽度。需结合 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)
  • 触摸屏支持:添加 touchstarttouchmove 事件处理
  • 持久化:通过 localStorage 保存用户调整后的宽度
  • 性能优化:使用 requestAnimationFrame 替代直接事件处理

完整示例扩展

// 持久化存储
mounted() {
  const savedWidth = localStorage.getItem('sidebarWidth');
  if (savedWidth) this.sidebarWidth = parseInt(savedWidth);
},
watch: {
  sidebarWidth(newVal) {
    localStorage.setItem('sidebarWidth', newVal);
  }
}

通过组合这些方法,可以实现一个可拖动、可记忆用户设置的侧边栏组件。实际应用中可根据需求调整细节参数。

标签: 侧边拖动
分享给朋友:

相关文章

vue实现拖动宽度

vue实现拖动宽度

Vue 实现拖动调整宽度 在 Vue 中实现拖动调整宽度可以通过监听鼠标事件和使用 CSS 样式来实现。以下是具体实现方法: 使用鼠标事件监听 创建一个可拖动的分隔条,通过监听 mousedown、…

vue实现位移拖动

vue实现位移拖动

Vue 实现位移拖动的方法 使用鼠标事件实现拖动 在 Vue 中可以通过监听鼠标事件实现元素的位移拖动。需要监听 mousedown、mousemove 和 mouseup 事件来跟踪拖动过程。 &…

vue 实现侧边栏

vue 实现侧边栏

使用 Vue 实现侧边栏 基于 Vue Router 的侧边栏导航 在 Vue 项目中,可以通过 Vue Router 结合组件化开发实现侧边栏导航。创建一个 Sidebar.vue 组件,动态渲染路…

vue表格宽度拖动实现

vue表格宽度拖动实现

vue表格宽度拖动实现 在Vue中实现表格宽度拖动功能,可以通过监听鼠标事件并结合CSS样式调整来实现。以下是具体实现方法: 使用原生事件监听 创建一个可拖动的列分隔线,通过监听mousedown、…

vue怎么实现拖动组件

vue怎么实现拖动组件

Vue 拖动组件实现方法 使用 HTML5 原生拖放 API 在 Vue 中可以利用 HTML5 的拖放 API 实现基础拖动功能。通过 draggable 属性和相关事件(dragstart, dr…

js 实现 拖动

js 实现 拖动

实现拖动的核心方法 使用HTML5的拖放API实现拖动功能。主要涉及draggable属性、dragstart、dragover和drop事件。 // 设置元素为可拖动 document.getEl…