实现列表拖拽上移或者下移

118 阅读1分钟

实现列表拖拽上移或者下移

html

<ul>
  <li v-for="(item, index) in items"
      :key="item.id"
      :draggable="true"
      @dragstart="dragStart(index)"
      @dragover.prevent
      @drop="drop(index)">
    {{ item.text }}
  </li>
</ul>

js

draggedItem: null,
draggingIndex: -1,
items: [
  { id: 1, text: 'Item 1' },
  { id: 2, text: 'Item 2' },
  { id: 3, text: 'Item 3' },
  { id: 4, text: 'Item 4' }
],
//方法
  dragStart(index) {
    this.draggedItem = this.items[index];
    this.draggingIndex = index;
  },
  drop(index) {
    const draggedIndex = this.items.indexOf(this.draggedItem);
    this.items.splice(draggedIndex, 1);
    this.items.splice(index, 0, this.draggedItem);
    this.draggingIndex = -1;
},