需求場(chǎng)景:
表格可以實(shí)現(xiàn)上下拖拽row實(shí)現(xiàn)新排序
首先,安裝sortable.js
npm install sortablejs --save
?引入表格排?
// 引入表格排序
import Sortable from 'sortablejs';
全局掛在組件
Vue.component('Sortable', Sortable)
使用頁(yè)面引入
import Sortable from 'sortablejs'
使用sortable.js表格一定要有唯一的row-key,一般綁定的是id,不然拖拽會(huì)不生效
data聲明
sortableContainer: null,為的是后面如果有需要可以做銷毀操作
?
因?yàn)槲疫@里是表格組件,所以有些需要自己適當(dāng)調(diào)整一下文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-836416.html
created(){
this.getSortTableData();
},
// 更新表格
getSortTableData() {
this.$nextTick(()=>{
setTimeout(() => {
if(this.isSortTable) {
let tableStyle = document.querySelector(`#${this.tableId} .el-table`);
tableStyle.style.cursor = 'pointer';
this.rowDrop();
}
}, 500)
})
},
// 行拖拽
rowDrop() {
console.log('行拖拽啟動(dòng)成功');
// 拖拽必須給對(duì)應(yīng)表格一個(gè)唯一的樣式id值
const tbody = document.querySelector(`#${this.tableId} .el-table__body-wrapper tbody`);
console.log('tbody', tbody)
const that = this;
this.sortableContainer = Sortable.create(tbody, {
forceFallback:true,
animation: 150,
dragClass: 'dragClass',
chosenClass: 'chosenClass',
ghostClass: "ghostClass",
// 結(jié)束拖拽后的回調(diào)函數(shù)
onEnd({ newIndex, oldIndex }) {
console.log('拖動(dòng)了行,序號(hào)(index)"'+ oldIndex + '"拖動(dòng)到序號(hào)(index)"' + newIndex+'"');
// 將oldIndex位置的數(shù)據(jù)刪除并取出,oldIndex后面位置的數(shù)據(jù)會(huì)依次前移一位
const currentRow = that.tableData.splice(oldIndex, 1)[0];
console.log('currentRow', currentRow)
// 將被刪除元素插入到新位置(currRow表示上面的被刪除數(shù)據(jù))
that.tableData.splice(newIndex, 0, currentRow);
console.log("拖動(dòng)后的新數(shù)組:", that.tableData)
// 拖拽結(jié)束后的回調(diào)函數(shù)
let params = {
// 拖動(dòng)后的新序號(hào)
newIndex,
// 拖動(dòng)了哪個(gè)序號(hào)
oldIndex,
// 當(dāng)前行
currentRow,
// 拖動(dòng)后的新數(shù)組
tableData: that.tableData
}
that.$emit('sortableRowDrop', params);
}
})
},
// 銷毀拖拽
destroySortTableData() {
this.sortableContainer.destroy();
let tableStyle = document.querySelector(`#${this.tableId} .el-table`);
tableStyle.style.cursor = 'default';
console.log('銷毀拖拽')
},
編輯文章實(shí)屬不易,如有幫助請(qǐng)點(diǎn)贊收藏~文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-836416.html
到了這里,關(guān)于隨手記:使用sortable.js 實(shí)現(xiàn)element-ui el-table 表格上下拖拽排序的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!