Search code examples
vue.jsvuetify.jsdraggable

Vue draggable to follow v-chip-group selection


I am using Vue draggable to change the position of my v-chips. When you click on a chip, the chip shows Active and is binded to selection with its index. The problem is that when you drag a chip and change its position it does not update the selection index.

How can I make sure one follows the other?

<v-chip-group
        v-model="selection"
        active-class="primary--text"
        column
>
    <draggable v-model="items" @start="drag=true" @end="drag=false">
        <v-chip v-for="(item, i) in items" :key="i"
                close
                draggable>
            {{item.name}}
        </v-chip>
    </draggable>
</v-chip-group>

Solution

  • You can able to set the selection index using @start and @end event in draggable component

    Here is the working codepen: https://codepen.io/chansv/pen/zYvOYyd?editors=1010

    Find the working code here:

        <div id="app">
      <v-app id="inspire">
        <v-card 
          max-width="400"
          class="mx-auto"
        >
          <v-card-text>
            <v-chip-group
              v-model="selection"
              column
              active-class="primary--text"
            >
              <draggable v-model="tags" @start="dragStart" @end="dragEnd">
                <v-chip v-for="(tag, i) in tags" :key="i" draggable>
                  {{ tag.name }}
                </v-chip>
              </draggable>
            </v-chip-group>
          </v-card-text>
        </v-card>
      </v-app>
    </div>
    
    
    new Vue({
      el: '#app',
      vuetify: new Vuetify(),
      data: () => ({
        selection: null,
        currentTag: null,
        tags: [{
          name: 'Shoping',
        },{
          name: 'Art',
        }, {
          name: 'Tech',
        }, {
          name: 'Creative Writing'
        }
        ],
      }),
      methods: {
        dragStart() {
          if (this.tags[this.selection]) this.currentTag = this.tags[this.selection].name;
          else this.currentTag = null;
        },
        dragEnd() {
          var self = this;
          if (this.currentTag) {
            this.tags.forEach((x, i) => {
              if (x.name === self.currentTag) self.selection = i;
            });  
          }
    
        }
      }
    })