当前位置:首页 > VUE

vue实现左右拉伸

2026-03-07 18:05:18VUE

实现左右拉伸布局

在Vue中实现左右拉伸布局可以通过CSS Flexbox或Grid结合Vue的响应式数据绑定完成。以下是两种常见方法:

vue实现左右拉伸

使用Flexbox布局

通过CSS Flexbox实现左右面板可拉伸,中间添加拖拽条控制宽度:

vue实现左右拉伸

<template>
  <div class="container">
    <div class="left-panel" :style="{ width: leftWidth + 'px' }">
      <!-- 左侧内容 -->
    </div>
    <div 
      class="drag-bar" 
      @mousedown="startDrag"
    ></div>
    <div class="right-panel">
      <!-- 右侧内容 -->
    </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>
.container {
  display: flex;
  height: 100vh;
}
.left-panel {
  background: #f0f0f0;
  min-width: 100px;
}
.drag-bar {
  width: 8px;
  background: #ddd;
  cursor: col-resize;
}
.right-panel {
  flex: 1;
  background: #fff;
}
</style>

使用CSS Grid布局

CSS Grid提供更精确的列控制,适合复杂布局:

<template>
  <div 
    class="grid-container"
    :style="{
      'grid-template-columns': `${leftWidth}px 8px 1fr`
    }"
  >
    <div class="left">
      <!-- 左侧内容 -->
    </div>
    <div 
      class="divider"
      @mousedown="startDrag"
    ></div>
    <div class="right">
      <!-- 右侧内容 -->
    </div>
  </div>
</template>

<style>
.grid-container {
  display: grid;
  height: 100vh;
}
.divider {
  background: #ddd;
  cursor: col-resize;
}
</style>

注意事项

  • 拖拽过程中添加user-select: none防止文本选中
  • 移动端需要额外处理触摸事件
  • 可添加min-widthmax-width限制拉伸范围
  • 性能优化可考虑节流处理mousemove事件

扩展方案

对于需要保存布局状态的场景,可将宽度值存入localStorage或通过Vuex管理:

// 在created钩子中恢复宽度
created() {
  const savedWidth = localStorage.getItem('leftPanelWidth')
  if (savedWidth) this.leftWidth = Number(savedWidth)
},
// 在拖拽结束时保存
stopDrag() {
  localStorage.setItem('leftPanelWidth', this.leftWidth)
}

标签: vue
分享给朋友:

相关文章

vue实现递归

vue实现递归

Vue 实现递归组件的方法 在 Vue 中实现递归组件通常用于处理树形结构数据(如菜单、评论列表、文件目录等)。以下是具体实现方法: 定义递归组件 通过 name 选项让组件可以递归调用自身: &…

vue实现影院

vue实现影院

Vue实现影院功能的基本思路 使用Vue框架开发影院功能需要结合前端组件化开发、状态管理以及后端API交互。以下是关键实现步骤: 影院页面布局设计 影院页面通常分为顶部导航栏、影院列表区域和底部导航…

vue实现导入

vue实现导入

Vue 实现文件导入功能 使用 <input type="file"> 元素 在 Vue 模板中添加一个文件输入元素,绑定 change 事件处理函数。 <template>…

vue实现系统

vue实现系统

Vue 实现系统的核心方法 使用 Vue.js 构建系统时,需结合其响应式特性与组件化开发模式。以下为关键实现路径: 项目初始化与工程配置 通过 Vue CLI 或 Vite 创建项目骨架,推荐选择…

vue 实现ztree

vue 实现ztree

在Vue中实现类似ZTree的功能,可以通过集成第三方库或自定义组件完成。以下是两种常见方法: 使用vue-tree组件 vue-tree是一个轻量级的Vue树形组件,支持复选框、懒加载等功能,适合…

vue实现插件

vue实现插件

Vue 插件实现方法 Vue 插件通常用于为 Vue 应用添加全局功能或共享功能。以下是实现 Vue 插件的核心步骤: 插件基本结构 Vue 插件需要暴露一个 install 方法,该方法接收 Vu…