当前位置:首页 > VUE

vue实现表格拖拽教程

2026-02-25 00:50:58VUE

Vue 表格拖拽实现方法

安装依赖库 推荐使用 vuedraggablesortablejs 实现拖拽功能。通过 npm 或 yarn 安装:

npm install vuedraggable
# 或
yarn add vuedraggable

基础表格拖拽实现 在 Vue 组件中引入 vuedraggable,绑定数据到表格:

<template>
  <draggable v-model="tableData" tag="table" item-key="id">
    <template #item="{ element }">
      <tr>
        <td>{{ element.id }}</td>
        <td>{{ element.name }}</td>
      </tr>
    </template>
  </draggable>
</template>

<script>
import draggable from 'vuedraggable'
export default {
  components: { draggable },
  data() {
    return {
      tableData: [
        { id: 1, name: 'Item 1' },
        { id: 2, name: 'Item 2' }
      ]
    }
  }
}
</script>

进阶功能配置 添加拖拽手柄和动画效果:

<draggable 
  v-model="tableData"
  handle=".handle"
  animation="200"
>
  <template #item="{ element }">
    <tr>
      <td><span class="handle">☰</span></td>
      <td>{{ element.name }}</td>
    </tr>
  </template>
</draggable>

跨表格拖拽实现 设置 group 属性实现表格间拖拽:

<draggable 
  v-model="list1" 
  group="tables" 
  @end="onDragEnd"
>
  <!-- 表格内容 -->
</draggable>

<draggable 
  v-model="list2" 
  group="tables"
>
  <!-- 表格内容 -->
</draggable>

与 Element UI 集成 在 Element UI 表格中使用拖拽:

<el-table :data="tableData" row-key="id">
  <el-table-column label="拖拽" width="80">
    <template #default>
      <i class="el-icon-rank" style="cursor: move"></i>
    </template>
  </el-table-column>
  <!-- 其他列 -->
</el-table>

<script>
import Sortable from 'sortablejs'
export default {
  mounted() {
    this.rowDrop()
  },
  methods: {
    rowDrop() {
      const tbody = document.querySelector('.el-table__body-wrapper tbody')
      Sortable.create(tbody, {
        onEnd: ({ newIndex, oldIndex }) => {
          const currRow = this.tableData.splice(oldIndex, 1)[0]
          this.tableData.splice(newIndex, 0, currRow)
        }
      })
    }
  }
}
</script>

注意事项

  • 确保为每行数据设置唯一的 key
  • 复杂场景建议使用 Sortable.js 原生库
  • 移动端需添加 touch 事件支持
  • 拖拽后及时更新后端数据

以上方法可根据实际需求组合使用,实现从简单到复杂的表格拖拽功能。

vue实现表格拖拽教程

标签: 表格拖拽
分享给朋友:

相关文章

vue实现简单表格

vue实现简单表格

Vue 实现简单表格的方法 使用原生 HTML 表格 在 Vue 模板中可以直接使用 HTML 原生表格标签,通过 v-for 动态渲染数据: <template> <tab…

vue实现表格拖动列宽

vue实现表格拖动列宽

实现表格列宽拖动的核心思路 通过监听鼠标事件(mousedown、mousemove、mouseup)实现拖拽逻辑,动态修改列宽。需要处理表头与表体的联动,确保拖动时视觉一致。 基础HTML结构…

css好看的表格制作

css好看的表格制作

使用CSS制作美观表格的方法 边框与间距优化 通过border-collapse属性合并边框,避免双边框效果。设置padding增加单元格内边距,提升可读性。 table { border…

vue实现子表格

vue实现子表格

实现子表格的基本思路 在Vue中实现子表格通常需要结合组件化思想和动态渲染技术。常见的场景是在主表格的行内嵌套子表格,展开主表行时显示对应的子表数据。 使用el-table实现子表格(Elemen…

vue 实现拖拽甘特图

vue 实现拖拽甘特图

实现拖拽甘特图的核心思路 Vue 实现拖拽甘特图需要结合第三方库或自定义逻辑,核心功能包括任务条渲染、时间轴刻度、拖拽交互、数据绑定等。以下是具体实现方法: 使用第三方库(推荐) vue-gan…

vue表格实现单选

vue表格实现单选

实现 Vue 表格单选功能 使用 v-model 绑定选中状态 在表格的每一行添加单选按钮或点击行触发选中,通过 v-model 绑定一个变量存储当前选中行的唯一标识(如 id)。 示例代码:…