Sortable.js是一款优秀的js拖拽库
官方Demo:http://rubaxa.github.io/Sortable/
sortable.js中文文档https://www.itxst.com/sortablejs/neuinffi.html
安装步骤:
npm install sortablejs --save
在.vue中的需要用到sorttable的vue文件中引入,也可以 在main.js中引入注册到Vue的根实例中
import Sortable from 'sortablejs'
<template>
<div style="width:800px">
<el-table :data="tableData" row-key="id" border align="left">
<el-table-column
prop="date"
label="日期"
width="180">
</el-table-column>
<el-table-column
prop="name"
label="姓名"
width="180">
</el-table-column>
<el-table-column
prop="address"
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: '王小虎AAA',
address: '沈阳市普陀区金沙江路2000-1518弄'
},
{
id: '2',
date: '2016-05-04',
name: '王小虎BBB',
address: '北京市普陀区金沙江路2020-1618弄'
},
{
id: '3',
date: '2016-05-01',
name: '王小虎CCC',
address: '成都市普陀区金沙江路2040-1718弄'
},
{
id: '4',
date: '2016-05-03',
name: '王小虎DDD',
address: '天津市普陀区金沙江路2030-1818弄'
}
]
}
},
mounted() {
this.rowDrop()
},
methods: {
//行拖拽
rowDrop() {
const tbody = document.querySelector('.el-table__body-wrapper tbody')
const _this = this
Sortable.create(tbody, {
animation: 150,
onEnd({ newIndex, oldIndex }) {
const currRow = _this.tableData.splice(oldIndex, 1)[0]
const aa= _this.tableData.splice(newIndex, 0, currRow)
console.log(aa)
}
})
},
//列拖拽 dropCol: [ { label:'日期', prop: 'date' }, { label: '姓名', prop: 'name' }, { label: '地址', prop: 'address'} ],
//列拖拽
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>
<style scoped>
</style>
效果图
**
注意
**
使用sortablejs时,在开发过程中出现了Sortable: el
must be an HTMLElement, not [object Null]的报错,记录一下我的解决方法:
如果table的值是在父组件传过来的,由于生命周期的原因在给对应table绑定方法时无法使用querySelector找到对应的table位置所以才会报这个错,所以在执行方法时候加上一个setTimeout就会解决