Search code examples
javascriptvue.jsonchangev-forvuedraggable

Vue draggable not updating index


I'm using Vue draggable to drag lists between categories:

<draggable v-bind="dragOptions" @change="dragCat">
   <div v-for="cat in categories" :key="cat.id">
      <draggable v-model="cat.lists" v-bind="dragOptions" 
         group="categories" @change="dragList(cat)">
         <div v-for="list in cat.lists" :key="list.id">
            {{list.title}}
         </div>
      </draggable>
   </div>
</draggable>
import draggable from "vuedraggable";
var vm = new Vue({
   el: "#app",
   components: {
      draggable
   },
   data() {
      return {
         categories: [
            {lists: [{title: "A"}, {title: "B"}]},
            {lists: [{title: "C"}, {title: "D"}]},
            {lists: [{title: "E"}, {title: "F"}]},
         ],
      }
   },
   methods: {
      dragCat() {
         // Loop through categories with index
         ...
      },
      dragList(cat) {
         // Loop through cat.lists with index
         ...
      },
   }
   ....
});

Because of group in the inner draggable I can drag between categories. But the outer draggable is not working, the change method is not called. When I use change instead, the categories do get moved and the function is called BUT the index in the loop is not updating.

Means: Initial 0(A,B) - 1(C,D) - 2 (E,F) I'll switch 0 and 1: Expected: 0(C,D) - 1(A,B) - 2(E,F) Reality: 1(C,D) - 0(A,B) - 2(E-F)

So I cannot send new index to database, means, when I move categories and refresh, it's back on initial state.


Solution

  • you're not binding categories to the outer draggable, adding v-model to first draggable will fix the issue, v-model="categories"

    also Using the proper key in a list may help, Vue needs the key to identify any change to a list