vue+elementUI实现表格拖拽

2021-09-18  本文已影响0人  陶菇凉

1.使用sortablejs的拖放排序列表的js插件;(http://www.sortablejs.com/index.html)来实现
UI框架是elementUI;在elementUI(ref="dragTable" row-key="id")是必须的

 <el-table ref="dragTable"  row-key="id" />

2.script代码,加载完数据之后,执行Sortable的方法

<script>
import Sortable from 'sortablejs'

export default {
  name: 'DragTable',
  data() {
    return {
      sortable: null,
      oldList: [],
      newList: []
    }
  },
 mounted(){
   this.setSort()
},
  methods: {
    setSort() {
      const el = this.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData: function(dataTransfer) {
          // to avoid Firefox bug
          // Detail see : https://github.com/RubaXa/Sortable/issues/1012
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
        //操作数据
          const targetRow = this.list.splice(evt.oldIndex, 1)[0]
          this.list.splice(evt.newIndex, 0, targetRow)

          // for show the changes, you can delete in you code
          const tempIndex = this.newList.splice(evt.oldIndex, 1)[0]
          this.newList.splice(evt.newIndex, 0, tempIndex)
        }
      })
    }
  }
}
</script>

上一篇下一篇

猜你喜欢

热点阅读