1. インストール
npm install sortablejs --save-dev
2.使用する
<template>
<div class="app-container">
<template>
<el-table
:data="tableData"
row-key="id"
style="width: 100%"
>
<el-table-column
v-for="(item, index) in col"
:key="`col_${index}`"
:prop="dropCol[index].prop"
:label="item.label"
/>
</el-table>
</template>
</div>
</template>
<script>
import Sortable from 'sortablejs'
export default {
name: 'DragTable',
data() {
return {
col: [
{
label: '日期',
prop: 'date'
},
{
label: '姓名',
prop: 'name'
},
{
label: '地址',
prop: 'address'
}
],
dropCol: [
{
label: '日期',
prop: 'date'
},
{
label: '姓名',
prop: 'name'
},
{
label: '地址',
prop: 'address'
}
],
tableData: [{
id: '1',
date: '2016-05-02',
name: '王小虎',
address: '上海市普陀区金沙江路 1518 弄'
}, {
id: '2',
date: '2016-05-04',
name: '王小虎',
address: '上海市普陀区金沙江路 1517 弄'
}, {
id: '3',
date: '2016-05-01',
name: '王小虎',
address: '上海市普陀区金沙江路 1519 弄'
}, {
id: '4',
date: '2016-05-03',
name: '王小虎',
address: '上海市普陀区金沙江路 1516 弄'
}]
}
},
mounted() {
// 阻止默认行为
document.body.ondrop = function(event) {
event.preventDefault()
event.stopPropagation()
}
this.rowDrop()
this.columnDrop()
},
methods: {
// 行拖拽
rowDrop() {
const tbody = document.querySelector('.el-table__body-wrapper tbody')
const _this = this
Sortable.create(tbody, {
onEnd({ newIndex, oldIndex }) {
const currRow = _this.tableData.splice(oldIndex, 1)[0]
_this.tableData.splice(newIndex, 0, currRow)
}
})
},
// 列拖拽
columnDrop() {
const wrapperTr = document.querySelector('.el-table__header-wrapper tr')
this.sortable = Sortable.create(wrapperTr, {
animation: 180,
delay: 0,
onEnd: evt => {
const oldItem = this.dropCol[evt.oldIndex]
this.dropCol.splice(evt.oldIndex, 1)
this.dropCol.splice(evt.newIndex, 0, oldItem)
}
})
}
}
}
</script>
予防:
dropCol と col は 2 つの異なる配列であり、1 つの配列に統合することはできません。1 つはタイトルの並べ替え用で、もう 1 つは列データの並べ替え用です。
ドラッグのオンとオフを切り替える:
ユーザーがクリックして調整を有効にすると、注文を調整できますが、閉じることはできません. インターネットで多くの情報を読んだ後、次の操作で問題を解決できます.
this.tableObject = Sortable.create(tbody, {
onEnd: ({ newIndex, oldIndex }) => {
const currRow = this.tableData.splice(oldIndex, 1)[0]
this.tableData.splice(newIndex, 0, currRow)
}
})
最初にドラッグ可能オブジェクトをオブジェクトに入れます (ここでは tableObject と名付けました)。ユーザーがクリックして調整を閉じたら、次を使用します。
this.tableObject.destroy()
このオブジェクトを破壊するには!