Vuetify テーブル並び替え

アプリ開発

Vuetify の v-simple-table で、マウスドラッグによる行の並び替え方法。

スポンサーリンク

環境

  • Windows 11 Home 21H2
  • Vue 2.6.14
  • Vuetify 2.6.0

コード

<template>
  <v-container>
    <v-row>
      <v-col cols="auto">
        <div class="my-parts">
          <v-simple-table>
            <template v-slot:default>
              <thead>
                <tr>
                  <th class="text-left">Name</th>
                  <th class="text-left">Calories</th>
                </tr>
              </thead>
              <transition-group name="fruits-list" tag="tbody">
                <tr
                  v-for="(item, index) in desserts"
                  :key="item.name"
                  draggable
                  @dragstart="dragList($event, index)"
                  @drop="dropList($event, index)"
                  @dragover.prevent
                  @dragenter.prevent
                >
                  <td>{{ item.name }}</td>
                  <td>{{ item.calories }}</td>
                </tr>
              </transition-group>
            </template>
          </v-simple-table>
        </div>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
export default {
  name: "HelloWorld",

  data: () => ({
    desserts: [
      { name: "Frozen Yogurt", calories: 159 },
      { name: "Ice cream sandwich", calories: 237 },
      { name: "Eclair", calories: 262 },
      { name: "Cupcake", calories: 305 },
    ],
  }),
  methods: {
    dragList(event, dragIndex) {
      event.dataTransfer.effectAllowed = "move";
      event.dataTransfer.dropEffect = "move";
      event.dataTransfer.setData("drag-index", dragIndex);
    },
    dropList(event, dropIndex) {
      const dragIndex = event.dataTransfer.getData("drag-index");
      const deleteList = this.desserts.splice(dragIndex, 1);
      this.desserts.splice(dropIndex, 0, deleteList[0]);
    },
  },
};
</script>

<style scoped>
.fruits-list-move {
  transition: transform 0.3s;
}
.my-parts td {
  border-left: thin solid rgba(0, 0, 0, 0.12);
}
.my-parts td:last-child {
  border-right: thin solid rgba(0, 0, 0, 0.12);
}
.my-parts tr:last-child td {
  border-bottom: thin solid rgba(0, 0, 0, 0.12);
}
</style>

実行

タイトルとURLをコピーしました