表格的拖拽排序功能---应用splice方法

1.引入sortablejs文件

import Sortable from 'sortablejs'

2.代码---合理运用splice方法,删掉旧索引的对象,再以新索引把旧对象重新加回去

  methods: {
    async getList() {
      this.listLoading = true
      const { data } = await fetchList(this.listQuery)
      console.log(data);
      this.list = data.items
      this.total = data.total
      this.listLoading = false
      this.oldList = this.list.map(v => v.id)
      this.newList = this.oldList.slice()
      console.log(this.oldList);
      console.log(this.newList);
      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', // 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 => {

          // targetRow为删掉的某个旧对象
          const targetRow = this.list.splice(evt.oldIndex, 1)[0]
          // 把删掉的某个就对象以新的index加入到list中
          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)
        }
      })
    }
  }
原文地址:https://www.cnblogs.com/pwindy/p/14832366.html