I have an array of objects:
ruta: [
{ 'order': 1, 'id': 121 },
{ 'order': 2, 'id': 123 }
]
I use it as a model for a buefy table and at the same time, I'm using the extension sortable.js to manually order the table rows:
const createSortable = (el, options, vnode) => {
return Sortable.create(el, {
...options,
onEnd: function (evt) {
const data = vnode.context.ruta
const item = data[evt.oldIndex]
if (evt.newIndex > evt.oldIndex) {
for (let i = evt.oldIndex; i < evt.newIndex; i++) {
data[i] = data[i + 1]
}
} else {
for (let i = evt.oldIndex; i > evt.newIndex; i--) {
data[i] = data[i - 1]
}
}
data[evt.newIndex] = item
//here
for (let i = 0; i < data.length; i++) {
data[i].order = i + 1;
}
}
})
}
The table is rendered correctly, but I need to update the order parameter on each manually sorting to reflect the real order o the table. For example, I need to move the fifth row to the beginning of the table, so its order parameter should be 1 and the rest of the rows need to reflect 2, 3, 4 and 5.
As you can see in the code, I've tried:
for (let i = 0; i < data.length; i++) {
data[i].order = i + 1;
}
Because I want to start from 1 the value of the order. I also tried to put the change into the if / else blocks:
if
data[i].order = i + 1;
else
data[i].order = i - 1;
But it didn't work either. The order of the rows is changed in a wrong way.
You already asked this on the Spanish SO site and I gave you a solution there. I know that you already solved the issue, but I'm going to post another solution to your question because it might be useful to other users in the future.
First of all, I already explained to you why this issue occurs: if you change the order of the model changing the values of its indexes,
Vuewill not detect the change, you need to modify thearrayin another way, for example, making ansplice. In your code,Vuedetects a change only when you change theorderparameter and at that moment the list is manually sorted, and the values of each index of thearrayhave changed, so, the view will be updated wrongly:The solution that I gave you before:
Working example: https://codepen.io/elchininet/pen/JLQqEV
Another solution:
Another solution is to reset the manually sorting after each movement and change the
arrayorder using asplice. Take a look:Here you have a working example: https://codepen.io/elchininet/pen/MVNaON