官網:http://www.sortablejs.com/index.html
Sortable.js是一款輕量級的拖放排序串列的js插件,支持ie9及以上版本ie瀏覽器和現代瀏覽器,也可以運行在移動觸摸設備中,不依賴jQuery,支持 Meteor、AngularJS、React、Vue、Knockout框架和任何CSS庫,如Bootstrap、Element UI,你可以用來拖拽div、table等元素,
npm下載
npm install sortablejs --save
vue參考
import Sortable from 'sortablejs'
GitHub專案Demo地址:https://github.com/Beingyo/vue-test-template/tree/main/src/page/sortable
示例:

重點:el-table的row-key必填,否則資料渲染會出錯
demo代碼:
<template>
<div>
<el-table
:data="https://www.cnblogs.com/bugSource/p/list"
:row-class-name="tableRowClassName"
row-key="id"
style="width: 1000px;margin: 0 auto">
<el-table-column
type="index"
label="下標"
align="center"
width="300">
</el-table-column>
<el-table-column
v-for="(label,index) in labels"
:key="index"
:label="label.label"
:prop="label.prop"
align="center">
</el-table-column>
</el-table>
</div>
</template>
<script>
import Sortable from 'sortablejs'
export default {
name: 'sortable',
data() {
return {
// list: [],
list: [
{index: '', id: 1, classifyName: '111111111111'},
{index: '', id: 2, classifyName: '222222222222'},
{index: '', id: 3, classifyName: '333333333333'},
{index: '', id: 4, classifyName: '444444444444'},
{index: '', id: 5, classifyName: '555555555555'},
{index: '', id: 6, classifyName: '666666666666'},
{index: '', id: 7, classifyName: '777777777777'},
{index: '', id: 8, classifyName: '888888888888'}
],
indexList: [],
labels: [
{label: 'ID', prop: 'id'},
{label: '分類名', prop: 'classifyName'}
]
}
},
mounted() {
const tbody = document.querySelector('.el-table__body-wrapper tbody')
const _this = this
Sortable.create(tbody, {
onEnd({newIndex, oldIndex}) {
var $li = tbody.children[newIndex]
var $oldLi = tbody.children[oldIndex]
// 先洗掉移動的節點
tbody.removeChild($li)
// 再插入移動的節點到原有節點,還原了移動的操作
if (newIndex > oldIndex) {
tbody.insertBefore($li, $oldLi)
} else {
tbody.insertBefore($li, $oldLi.nextSibling)
}
// 更新items陣列
const currRow = _this.list.splice(oldIndex, 1)
_this.list.splice(newIndex, 0, currRow[0])
// 下一個tick就會走patch更新
for (var i = 0; i < _this.list.length; i++) {
_this.list[i].index = _this.indexList[i]
}
console.log('傳輸資料:')
console.log(JSON.stringify(_this.list))
},
animation: 150
})
},
methods: {
tableRowClassName({rowIndex}) {
// 把每一行的索引放進row
this.indexList[rowIndex] = rowIndex
}
}
}
</script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/270844.html
標籤:Html/Css
下一篇:Vue中bus的使用
