要求是既能行拖拽,又能列拖拽
其實(shí)自己實(shí)現(xiàn)起來(lái)特別簡(jiǎn)單,沒(méi)必要在一些UI插件上二次開(kāi)發(fā).
1.vue2的例子
安裝sortablejs
npm install sortablejs --save
如果想拖拽列,就在列的上一級(jí)元素tr給個(gè)id,傳入sortablejs實(shí)例就行.
如果想拖拽行,就在行的上一級(jí)元素tbody綁定個(gè)id,傳入sortablejs實(shí)例
具體代碼如下
<template>
<div>
demo
<table class="table table-striped">
<thead class="thead-dark">
<tr class="sort-target" id="tuo_1">
<th class="cursor-move" v-for="header in columns" :key="header.key">
{{ header.title }}
</th>
</tr>
</thead>
<tbody id="neirong_1">
<tr v-for="(item, index) in list" :key="index">
<td v-for="header in columns" :key="header.key">
{{ item[header.dataIndex] }}
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import Sortable from "sortablejs";
export default {
data() {
return {
columns: [
{
title: "年齡",
dataIndex: "age",
key: "age"
},
{
title: "班級(jí)",
dataIndex: "banji",
key: "banji"
},
{
title: "成績(jī)",
dataIndex: "chengji",
key: "chengji"
}
],
list: [
{
age: 17,
banji: "a1-17",
chengji: 57
},
{
age: 18,
banji: "a2-18",
chengji: 58
},
{
age: 19,
banji: "a3-19",
chengji: 59
},
{
age: 20,
banji: "a4-20",
chengji: 60
}
]
};
},
mounted(){
this.lie_sort()
this.hang_sort()
},
methods: {
lie_sort() {
let el = document.getElementById("tuo_1");
Sortable.create(el, {
animation: 300,
onEnd: evt => {
// 獲取拖動(dòng)前和拖動(dòng)后的行索引——可以直接在這里拿到對(duì)應(yīng)的列和排序后的位置進(jìn)行保存
const oldIndex = evt.oldIndex;
const newIndex = evt.newIndex;
console.log(oldIndex,newIndex)
// 根據(jù)行索引交換數(shù)據(jù)
if (oldIndex !== newIndex) {
this.columns.splice(newIndex, 0, this.columns.splice(oldIndex, 1)[0]);
}
// 這里后面的數(shù)據(jù)tableData就是排序后的表格列表了,可以直接進(jìn)行保存
console.log("列 切換位置后的數(shù)據(jù)", this.columns);
}
});
},
hang_sort() {
let el_hang = document.getElementById("neirong_1");
Sortable.create(el_hang, {
animation: 300,
onEnd: evt => {
// 獲取拖動(dòng)前和拖動(dòng)后的行索引——可以直接在這里拿到對(duì)應(yīng)的列和排序后的位置進(jìn)行保存
const oldIndex = evt.oldIndex;
const newIndex = evt.newIndex;
console.log(oldIndex,newIndex)
// 根據(jù)行索引交換數(shù)據(jù)
if (oldIndex !== newIndex) {
this.list.splice(newIndex, 0, this.list.splice(oldIndex, 1)[0]);
}
// 這里后面的數(shù)據(jù)tableData就是排序后的表格列表了,可以直接進(jìn)行保存
console.log("行 切換位置后的數(shù)據(jù)", this.list);
}
});
},
}
};
</script>
<style scoped lang="less">
table {
tr td {
padding: 10px;
}
}
</style>