首页 > 编程 > JavaScript > 正文

sortable+element 实现表格行拖拽的方法示例

2019-11-19 11:22:50
字体:
来源:转载
供稿:网友

背景

1、vue项目中的表格需要实现行拖拽功能

2、表格使用element组件库中el-table

方案介绍

Sortable.js

介绍:Sortable.js是一款轻量级的拖放排序列表的js插件

引用自官方文档:No jQuery required. Supports Meteor, AngularJS, React, Polymer, Vue, Knockout and any CSS library, e.g. Bootstrap.

参考地址: https://github.com/SortableJS/Sortable

vuedraggable
介绍:基于Sortable.js的vue组件,用以实现拖拽功能

引用自官方文档:Vue drag-and-drop component based on Sortable.js

参考地址: https://github.com/SortableJS/Vue.Draggable

遇到的问题
在使用vuedraggable的过程中,发现必须用<draggable></draggable>包裹拖动项的父级元素,但是element组件库对table进行封装,无法直接包裹拖动项(即tr)的父级元素

如果你的项目中,表格未使用组件库,实现可以参考 https://www.VeVB.COm/article/162648.htm

解决方案

使用 sortable.js

步骤一: 安装

npm install vuedraggable

步骤二:引入

import Sortable from 'sortablejs';@Component({ components: {  Sortable }})

步骤三: el-table 添加row-key属性

<el-table ref="filterTable" row-key="ip"  @filter-change="handlerFilterChange"  class="cl-table"  :data="resourceList"  v-loading="resourceListLoading"  stripe style="width:100%;"> <el-table-column   prop="name"  label="主机名"   :min-width="150"   show-overflow-tooltip> </el-table-column> </el-table>

步骤四 : 将拖拽元素设置为要拖动项的父级元素

mounted() {   // 表格中需要实现行拖动,所以选中tr的父级元素  const table = document.querySelector('.el-table__body-wrapper tbody')  const self = this  Sortable.create(table, {   onEnd({ newIndex, oldIndex }) {    console.log(newIndex, oldIndex)    const targetRow = self.resourceList.splice(oldIndex, 1)[0]    self.resourceList.splice(newIndex, 0, targetRow)   }  }) }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表