Reputation: 2263
I have a list which is sortable with drag and drop. And it works https://codepen.io/destroy90210/pen/rGEodB
Now I wanted to include the feature to sort the list by name, date and position.
So if i see the list sorted by name or date i block the drag an drop functionality. Only if position is selected, from the dropdown, the items are dragable, but now my drag and drop doesn't work any more. The items jump back to the old position...
https://codepen.io/destroy90210/pen/yzdQxK
<div id="main">
<select class="dd" v-model="orderBy" @change="sortedData">
<option value='created'>created</option>
<option value='abc'>Abc</option>
<option value='position'>Position</option>
</select>
<draggable :list="data" class="dragArea" @change="changeOrder" :options="{draggable:'.card--dragable'}">
<div :class="{'card--dragable': isDragable}" class="card" v-for="item in sortedData"><span class="card__label">{{item.name}}</span></div>
</draggable>
</div>
new Vue({
el: "#main",
data: {
data: data,
orderBy: 'position',
isDragable: true,
},
computed:{
sortedData(){
this.isDragable = false;
if (this.orderBy === 'abc') {
return this.data.sort((a, b) => { return a.name.localeCompare(b.name); });
} else if (this.orderBy === 'created') {
return this.data.sort((a, b) => { return a.id > b.id; });
}
this.isDragable = true;
return this.data.sort((a, b) => { return a.position > b.position; });
},
},
methods:{
changeOrder(e){
const oldIndex = e.moved.oldIndex;
const newIndex = e.moved.newIndex;
let i = Math.min(oldIndex, newIndex);
const max = Math.max(oldIndex, newIndex) + 1;
for (i; i < max; i += 1) {
this.data[i].position = i;
}
}
}
});
Upvotes: 0
Views: 611
Reputation: 904
Fix: https://codepen.io/destroy90210/pen/jGgNBN
sortedData()
is a computed element in your codepen, this means it will execute when its dependencies update (in your case when changeOrder()
gets executed on a drag/drop action).
Use a method instead so it only executes when your select is updated by the following change event:
<select class="dd" v-model="orderBy" @change="sortedData">
This means we can fix the issue by moving sortedData()
from computed to methods.
Now it wont update on a drop anymore.
Documentation about computed vs methods.
Upvotes: 1