[Vuejs]-How to move rows up & down using v-data-table?

0👍

You can take a look at this example. The example has up and down arrow which you will click and it will update the items array. Note that you must you use Vue.$set to make the update to the items array reactive.

The example is done using vue-composition api and typescript

https://gist.github.com/JeremyWalters/457ea585bab678b3bafeb3ee16e96401

<template>
    <v-data-table :headers="headers" :items="items">
      <template v-slot:item.actionUp="{item}">
        <v-btn color="success" icon @click="moveUp(item.id)">
          <v-icon>mdi-arrow-up</v-icon>
        </v-btn>
      </template>
      <template v-slot:item.actionDown="{item}">
        <v-btn color="warning" icon @click="moveDown(item.id)">
          <v-icon>mdi-arrow-down</v-icon>
        </v-btn>
      </template>
    </v-data-table>
</template>

<script lang="ts">
import {
  defineComponent,
  SetupContext,
  ref,
  onMounted,
  Ref
} from "@vue/composition-api";
export default defineComponent({
  setup(props: any, context: SetupContext) {
    const items: Ref<any[]> = ref([]);
    const headers = [
      { text: "Test Value", value: "testValue" },
      { text: "", value: "actionUp" },
      { text: "", value: "actionDown" }
    ];
    // Create data example
    onMounted(() => {
      for (let i = 0; i < 20; i++) {
        items.value.push({ id: i, testValue: "testValue " + i });
      }
    });

    // Move items up in the array
    function moveUp(id: number) {
      const index = items.value.findIndex(e => e.id == id);
      if (index > 0) {
        const el = items.value[index];
        context.root.$set(items.value, index, items.value[index - 1]);
        context.root.$set(items.value, index - 1, el);
      }
    }
    // Move items down in the array
    function moveDown(id: number) {
      const index = items.value.findIndex(e => e.id == id);
      debugger;
      if (index !== -1 && index < items.value.length - 1) {
        const el = items.value[index];
        context.root.$set(items.value, index, items.value[index + 1]);
        context.root.$set(items.value, index + 1, el);
      }
    }
    return {
      moveUp,
      moveDown,
      headers,
      items
    };
  }
});
</script>

Leave a comment