vue表格拖拽使用Sortable插件库
1 <template > 2 <el-table 3 row-key="name" 4 :data="tableData" 5 stripe style="width:100%;"> 6 <el-table-column prop="name" label="测试"></el-table-column> 7 </el-table> 8 </template> 9 10 <script> 11 import Sortable from 'sortablejs' 12 13 export default { 14 data() { 15 return { 16 tableData: [ 17 { 18 name: '凯小默111' 19 }, 20 { 21 name: '凯小默222' 22 }, 23 { 24 name: '凯小默333' 25 }, 26 { 27 name: '凯小默444' 28 }, 29 { 30 name: '凯小默555' 31 } 32 ] 33 } 34 }, 35 mounted() { 36 //使每次都可以拖拽 37 this.$nextTick(()=>{ 38 setTimeout(()=>{ 39 this.rowDrop(); 40 },100) 41 }) 42 }, 43 methods: { 44 //行拖拽 45 rowDrop() { 46 const tbody = document.querySelector('.el-table__body-wrapper tbody') 47 Sortable.create(tbody, { 48 onEnd:({ newIndex, oldIndex })=> { 49 const currRow = this.tableData.splice(oldIndex, 1)[0]; 50 this.tableData.splice(newIndex, 0, currRow); 51 console.log(this.tableData); 52 } 53 }) 54 }, 55 } 56 } 57 </script>
如果碰到了火狐浏览器拖动会在新窗口打开并去百度进行搜索等问题,如下解决方式:
mounted() {
document.body.ondrop = function (event) {
event.preventDefault()
event.stopPropagation()
}
<template >
<el-table
row-key="name"
:data="tableData"
stripe style="width:100%;">
<el-table-column prop="name" label="测试"></el-table-column>
</el-table>
</template>
<script>
import Sortable from 'sortablejs'
export default {
data() {
return {
tableData: [
{
name: '凯小默111'
},
{
name: '凯小默222'
},
{
name: '凯小默333'
},
{
name: '凯小默444'
},
{
name: '凯小默555'
}
]
}
},
mounted() {
//使每次都可以拖拽
this.$nextTick(()=>{
setTimeout(()=>{
this.rowDrop();
},100)
})
},
methods: {
//行拖拽
rowDrop() {
const tbody = document.querySelector('.el-table__body-wrapper tbody')
Sortable.create(tbody, {
onEnd:({ newIndex, oldIndex })=> {
const currRow = this.tableData.splice(oldIndex, 1)[0];
this.tableData.splice(newIndex, 0, currRow);
console.log(this.tableData);
}
})
},
}
}
</script>