Nathan Wailes
Nathan Wailes

Reputation: 12252

How can I reorder the items in a Vuetify data table by dragging the rows?

I'm working on a Vuetify web app for a client and she wants to be able to adjust the order of elements being displayed in a data table by dragging and dropping the rows, but the Vuetify documentation doesn't explain how to do that; how can I do it?

Upvotes: 7

Views: 8266

Answers (1)

Nathan Wailes
Nathan Wailes

Reputation: 12252

Here's a CodePen I got working: https://codepen.io/NathanWailes/pen/rNLajYO

It uses:

  • Vue 2.x
  • Vuetify 2.3.13
  • Sortable 1.10.2 (so you'll need to install/import this if you don't already have it)

It's based on the answers in this GitHub issue.

Here's the code:

<div id="app">
  <v-app>
    <v-data-table
      :headers="headers"
      :items="desserts"
      v-sortable-data-table
      @sorted="saveOrder"
      item-key="name"
    ></v-data-table>
  </v-app>
</div>

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data () {
    return {
      headers: [
        {
          text: 'Dessert',
          align: 'start',
          sortable: false,
          value: 'name',
        },
      ],
      desserts: [
        {
          name: 'Frozen Yogurt',
        },
        {
          name: 'Ice cream sandwich',
        },
        {
          name: 'Eclair',
        },
        {
          name: 'Cupcake',
        },
        {
          name: 'Gingerbread',
        },
      ],
    }
  },
  methods: {
    saveOrder (event) {
      const movedItem = this.desserts.splice(event.oldIndex, 1)[0];
      this.desserts.splice(event.newIndex, 0, movedItem);
    }
  },
  directives: {
    sortableDataTable: {
      bind (el, binding, vnode) {
        const options = {
          animation: 150,
          onUpdate: function (event) {
            vnode.child.$emit('sorted', event)
          }
        }
        Sortable.create(el.getElementsByTagName('tbody')[0], options)
      }
    }
  },
})

Upvotes: 16

Related Questions