最近遇到需求要求给 element 的 tabs 组件实现拖拽,通过查资料找到 Sortable 插件 此插件既能支持拖拽 tabs,也能支持拖拽 table,具体使用代码如下:
1.table 拖拽 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 <script> import { fetchList } from '@/api/article' import Sortable from 'sortablejs' export default { name : 'DragTable' , filters : { statusFilter (status ) { const statusMap = { published : 'success' , draft : 'info' , deleted : 'danger' } return statusMap[status] } }, data ( ) { return { list : null , total : null , listLoading : true , listQuery : { page : 1 , limit : 10 }, sortable : null , oldList : [], newList : [] } }, created ( ) { this .getList () }, methods : { async getList ( ) { this .listLoading = true const { data } = await fetchList (this .listQuery ) this .list = data.items this .total = data.total this .listLoading = false this .oldList = this .list .map (v => v.id ) this .newList = this .oldList .slice () this .$nextTick(() => { this .setSort () }) }, setSort ( ) { const el = this .$refs .dragTable .$el .querySelectorAll ('.el-table__body-wrapper > table > tbody' )[0 ] this .sortable = Sortable .create (el, { ghostClass : 'sortable-ghost' , setData : function (dataTransfer ) { dataTransfer.setData ('Text' , '' ) }, onEnd : evt => { const targetRow = this .list .splice (evt.oldIndex , 1 )[0 ] this .list .splice (evt.newIndex , 0 , targetRow) const tempIndex = this .newList .splice (evt.oldIndex , 1 )[0 ] this .newList .splice (evt.newIndex , 0 , tempIndex) } }) } } } </script> <style > .sortable-ghost { opacity : .8 ; color : #fff !important ; background : #42b983 !important ; } </style >
2.tabs 拖拽 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 import Sortable from "sortablejs" ; mounted ( ) { this .getList () } async getList ( ) { this .listLoading = true const { data } = await fetchList (this .listQuery ) this .list = data.items this .total = data.total this .listLoading = false this .oldList = this .list .map (v => v.id ) this .newList = this .oldList .slice () this .$nextTick(() => { this .setSort () }) } setSort ( ) { const el = document .querySelector (".el-tabs__nav" ); const that = this ; Sortable .create (el, { onEnd : (evt ) => { console .log ("change: " , evt.oldIndex , evt.newIndex ); const tempIndex = that.terminals .splice (evt.oldIndex , 1 )[0 ]; that.terminals .splice (evt.newIndex , 0 , tempIndex); }, }); }
更多强大的功能参照官网示例,这里不再赘述.