一、概述
Sortable.js
是一款优秀的js拖拽库,支持IE9及以上版本IE浏览器和现代浏览器,也可以运行在移动触摸设备中,不依赖jQuery
,支持AngularJS
、React
、Vue
框架和任何CSS
库,如bootstrap
、elementUI
,可以用来拖拽div
、table
等元素。
二、安装插件
npm i -S vuedraggable
vuedraggable
依赖Sortable.js
,我们可以直接引入Sortable使用Sortable的特性。vuedraggable
是Sortable
的一种加强,实现组件化的思想,可以结合Vue,使用起来更方便。
三、使用
需要注意的是:
el-table
必须指定row-key
,row-key
必须是唯一的,不然会出现排序不对的情况。- const currRow = _this.projectList.splice(oldIndex, 1)[0]
// 将oldIndex位置的数据删除并取出,oldIndex后面位置的数据会依次前移一位- _this.projectList.splice(newIndex, 0, currRow)
// 将被删除元素插入到新位置(currRow表示上面的被删除数据)
新建vue文件:
<template>
<div>
<el-table :data="tableData" row-key="id">
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="address" label="地址"></el-table-column>
<el-table-column prop="date" label="日期"></el-table-column>
</el-table>
</div>
</template>
<script>
import Sortable from 'sortablejs';
export default {
data() {
return {
tableData: [
{
id: '1',
date: '2016-05-02',
name: '王小虎1',
address: '上海市普陀区金沙江路 100 弄'
},
{
id: '2',
date: '2016-05-04',
name: '王小虎2',
address: '上海市普陀区金沙江路 200 弄'
},
{
id: '3',
date: '2016-05-01',
name: '王小虎3',
address: '上海市普陀区金沙江路 300 弄'
},
{
id: '4',
date: '2016-05-03',
name: '王小虎4',
address: '上海市普陀区金沙江路 400 弄'
}
],
col: [
{
label: '日期',
prop: 'date'
},
{
label: '姓名',
prop: 'name'
},
{
label: '地址',
prop: 'address'
}
],
dropCol: [
{
label: '日期',
prop: 'date'
},
{
label: '姓名',
prop: 'name'
},
{
label: '地址',
prop: 'address'
}
]
}
},
mounted() {
this.rowDrop();
this.columnDrop();
},
methods: {
// 行拖拽
rowDrop() {
// 要侦听拖拽响应的DOM对象(数据存储在.el-table__body-wrapper > .el-table__row > tbody标签中(el-table的数据部分的“最外层”class名为el-table__body-wrapper))
const tbody = document.querySelector('.el-table__body-wrapper tbody');
const that = this;
Sortable.create(tbody, {
// 结束拖拽后的回调函数
onEnd({ newIndex, oldIndex }) {
console.log('拖动了行,序号(index)"'+oldIndex+'"拖动到序号(index)"' + newIndex+'"');
const currentRow = that.tableData.splice(oldIndex, 1)[0]; // 将oldIndex位置的数据删除并取出,oldIndex后面位置的数据会依次前移一位
that.tableData.splice(newIndex, 0, currentRow); // 将被删除元素插入到新位置(currRow表示上面的被删除数据)
}
})
},
// 列拖拽
columnDrop() {
// 要侦听拖拽响应的DOM对象
const wrapperTr = document.querySelector('.el-table__body-wrapper tr');
const that = this;
Sortable.create(wrapperTr, {
animation: 180,
delay: 0,
// 结束拖拽后的回调函数
onEnd: evt => {
console.log('拖动了列(index):');
const oldItem = that.dropCol[evt.oldIndex];
that.dropCol.splice(evt.oldIndex, 1);
that.dropCol.splice(evt.newIndex, 0, oldItem);
}
})
}
}
}
</script>
——————————————————————
转载自,对原文代码有略微修改:el-table实现拖拽效果_el-table拖拽_柒个橙子的博客-CSDN博客