element ui 表格沒有自帶的拖拽排序的功能,只能借助第三方插件Sortablejs來實現,並實現禁止某列被拖拽,用了如下參數handle,filter,preventOnFilter,draggable,配置地址:http://www.sortablejs.com/options.html
1、npm安裝sortable.js
$ npm install sortablejs --save
2、新建一個公用組件 Sortable.vue
<template> <div></div> </template> <style> </style> <script> import Sortable from 'sortablejs' export default { data () { return { } }, props: [ 'tableData', 'dropCol','col' ], mounted () { console.log(this.tableData,this.dropCol); 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, handle: ".allowDrag", // 格式為簡單css選擇器的字符串,使列表單元中符合選擇器的元素成為拖動的手柄,只有按住拖動手柄才能使列表單元進行拖動 filter: ".noDrag", // 過濾器,不需要進行拖動的元素 preventOnFilter: true, // 在觸發過濾器`filter`的時候調用`event.preventDefault()` draggable: ".allowDrag", // 允許拖拽的項目類名 onEnd: evt => { const oldItem = this.dropCol[evt.oldIndex-1] -num是多少列被禁止 this.dropCol.splice(evt.oldIndex-1, 1) this.dropCol.splice(evt.newIndex-1, 0, oldItem) } }) } } } </script>
3、在需要得頁面應用組件
<template> <div> <sortableJs v-bind:tableData="tableData" v-bind:dropCol="dropCol" v-bind:col="col"></sortableJs> <el-table ref="multipleTable" :data="tableData" row-key="id" show-summary border stripe height="600" row-class-name="tableRow" header-row-class-name="tableHeader" @row-dblclick="handleSelectionChange" style="width: 100%; border-top: 1px solid #c5c5c5" > <el-table-column type="selection" class-name="noDrag" width="55"> </el-table-column> <!-- <el-table-column type="index" label="序號" width="55"> </el-table-column> --> <el-table-column v-for="(item, index) in col" :key="`col_${index}`" :prop="dropCol[index].propName" :label="item.title" class-name="allowDrag" width="150" > </el-table-column> </el-table> </div> </template>
col: [ { id: '1', title: '序號', propName: 'id', }, { id: '2', title: '時間', propName: 'date', }, { id: '3', title: '地址', propName: 'province', }, { id: '4', title: '星標', propName: 'city', }, { id: '5', title: '主題', propName: 'address', } ], dropCol: [ { id: '1', title: '序號', propName: 'id', }, { id: '2', title: '時間', propName: 'date', }, { id: '3', title: '地址', propName: 'province', }, { id: '4', title: '星標', propName: 'city', }, { id: '5', title: '主題', propName: 'address', } ], tableData: [ { date: '2016-05-02', id: '1', province: '地址11', city: '合作中', address: 'A類' }, { id: '2', date: '2016-05-04', province: '地址002', city: '未合作', address: 'A類' }, { id: '3', date: '2016-05-01', province: '地址11003', city: '中斷', address: 'A類',
}, { id: '4', date: '2016-05-03', province: '地址104', city: '未合作', address: 'A類', }, ],