Vuejs draggable sorted list

1.3k Views Asked by At

I'm using Vue.Draggable plugin to implement a draggable list. I'm passing a sorted computed property, like the following:

data(){

  return {

   paymentMethods: [
     { name: 'stripe', Dindex: 0, state: 2 },
     { name: 'paypal', Dindex: 1 , state: 1 },
     { name: '2checkout', Dindex: 2, state: 4 },
     { name: 'cod', Dindex: 3, state: 3 }
   ],
  }
},

computed: {

  payments() {
    return _.sortBy(this.paymentMethods, 'state');
  },
}

Draggable list:

<draggable :list="payments" class="payment-methods" tag="ul" @start="drag=true" @end="drag=false" @change="indexChanged">
   <li v-for="(method, index) in payments" :key="index">
        <!-- list data -->
   </li>
</draggable>

The problem here is the draggable list never works because i'm forcing the list sorting (using lodash _.sortBy), the question is how i can sort inside a draggable list.

2

There are 2 best solutions below

0
On

While it is a computed value the list will sorted again when you drag it. I think the best thing to do is sort it when mounted:(So only initially)

data() {
  return {
    payments: []
    paymentMethods: [
        { name: 'stripe', Dindex: 0, state: 2 },
        { name: 'paypal', Dindex: 1 , state: 1 },
        { name: '2checkout', Dindex: 2, state: 4 },
        { name: 'cod', Dindex: 3, state: 3 }
    ],
  }
}
mounted() {
    payments = _.sortBy(this.paymentMethods, 'state');
}
0
On

I know this is kind of old but I've also tried Googling for a solution and couldn't find any. A few minutes later I came up with this:

// <template />

<draggable
    class="drag-wrapper selected-cols"
    v-bind="dragOptions"
    ...other props
    @change="colChange"
>
    <div v-for="(col, i) in availableColumns" :key="col.name + '-' + i">
        <div class="drag-area">
            {{ col.label }}
        </div>
    </div>
</draggable>


// <scripts />

methods: {
    colChange(e) {
        this.availableColumns.sort((a, b) => 
           a.label.localeCompare(b.label));
        },
    },

So instead of using a computed for sorting, I just do the sorting in the @change listener since that is being called AFTER vuedraggable is done sorting.