下載插件 npm install sortable.js --save (下載的時候一定要這樣去下載,不要去下載 npm install sortable--save )
因為sortable.js和sortable是不一樣的哈
引入 import Sortable from 'sortablejs';
// 千萬不要加點.js 否者就會報錯create不是一個方法
注意 這個插件是不要注冊的哈。
需要注意的是element table務必指定row-key,row-key必須是唯一的,如ID,不然會出現排序不對的情況。
參考的地址 https://blog.csdn.net/qq_26440803/article/details/83663511
為啥一開始就在mounted中調用了兩個函數,不太懂?????
<template>
<div style="width:800px">
<el-table :data="tableData"
border
row-key="id"
align="left">
<el-table-column v-for="(item, index) in col"
:key="`col_${index}`"
:prop="dropCol[index].prop"
:label="item.label">
</el-table-column>
</el-table>
</div>
</template>
<script>
import Sortable from 'sortablejs'
export default {
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: '王小虎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 弄'
}
]
}
},
mounted() {
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>
https://www.cnblogs.com/xiangcheng618/p/10241090.html 這個地址也可以進行拖拽,明天去研究一下
在后來和產品的溝通中發現,並不是這樣的效果。
他希望排序后,做左邊的日期也能夠排序。
所以其他的都不改變,是改變這個rowDrop方法。
//行拖拽
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)
//對日期進行重新排序
for(let i=0;i<_this.tableData.length;i++){
_this.tableData[i].date=i+1;
}
}
})
},
如何達到產品說的那一種效果。我之前回來想了很久。都沒有做好.
今天忽然腦殼開竅了,就想明白了。
我覺得 思維靈活比是編成中最重要的,沒有之一哈。
需要注意一下,你在瀏覽器中是ok的;
但是你在火狐瀏覽器上會出現拖拽的時
火狐還是打開了一個新的tab,並且搜索了。
那么應該如何去解決呢???
created() {
document.body.ondrop = function (event) {
event.preventDefault();
event.stopPropagation();
}
},