It's great to have the
v-for directive, it's handiest directive that came out of the box with Vue.js.
But, what if we wanted to make this rendered list "sortable". Sure we can use the
Sortable library, but what if we wanted to make the order of the array elements two way binded (just like v-model)? Meaning that when you change the order in your Model, the HTML order will change (of course it will this is what vue does basically) and when you change the order in your HTML the order of the array will change.
v-for directive sortable is a three steps trick:
- Initialize Sortable library on the element
- Added a
movefunction to the
Array.prototype, so we can move an array element from one index to the other.
- Added a hook to the Sortable library to be called whenever the order of the HTML changes.
However, Vue 2 doesn't like the above code very much. if you apply the same previous example it will not work as expected, since it handles DOM diffing differently (claimed to be faster and more efficient than virtual DOM).
To work around this problem we need to add a unique identifier to our array items, and then bind this identifier to
key property in our HTML.