实现一个简易的antd表格拖拽

<a-table :columns="columns" :data-source="dataSource">
  <template slot="icon" slot-scope="record">
      <div
         style="cursor: pointer;"
         :draggable="true"
         @dragstart="dragstart(record, $event)"
         @dragenter="dragenter(record, $event)"
         @dragend="dragend(record, $event)"
         @dragover="dragover($event)"
         >
       <a-icon type="menu" />
     </div>
  </template>
  <template slot="action" slot-scope="record">
      <a @click="action(record)">操作</a>
  </template>
</a-table>
const columns = [
      {
        fixed: 'left',
        width: 50,
        key: 'icon',
        scopedSlots: { customRender: 'icon' },
      },
      {
        title: 'Full Name',
        dataIndex: 'name',
        width: 150,
        key: 'name',
      },
      {
        title: 'Age',
        dataIndex: 'age',
        width: 100,
        key: 'age',
      },
      {
        title: 'Action',
        key: 'operation',
        scopedSlots:{customRender:'action'},
        width: 100,
      },
    ]
data(){
    return{
        columns:[],
        // 数据
        dataSource: [],
        
        // 位置记录
        oldData: {},
        newData: {},
    }
}
       

 

mounted() {
    const data = []
    for (let i = 0; i < 100; i++) {
      data.push({
        key: i,
        name: `Edrward ${i}`,
        age: i + 1,
        address: `London Park no. ${i}`,
      })
    }
    this.dataSource = data
  },
methods: {
 // 拖拽
    dragstart(record, e) {
      this.oldData = record
    },
    // 记录移动过程中信息
    dragenter(record, e) {
      e.target.draggable = true
      this.newData = record
      e.preventDefault()
    },
    // 拖拽最终操作
    dragend(record, e) {
      if (this.oldData !== this.newData) {
        let oldIndex = this.dataSource.indexOf(this.oldData)
        let newIndex = this.dataSource.indexOf(this.newData)
        let newItems = [...this.dataSource]
        // 删除老的节点
        newItems.splice(oldIndex, 1)
        // 在列表中目标位置增加新的节点
        newItems.splice(newIndex, 0, this.oldData)
        this.dataSource = [...newItems]
      }
    },
    // 拖动事件(主要是为了拖动时鼠标光标不变为禁止)
    dragover(e) {
      e.preventDefault()
    },   
}

 

posted @ 2023-03-24 16:53  Private!  阅读(309)  评论(0编辑  收藏  举报