vue.jsdraggablevuejs3sortablejs

Draggable in Vue 3 won't display value


I am using Vue draggable to sort items from my Store.js by drag and drop (I've simplified my example here using only ['a', 'b', 'c'] as my store data).

I am also using a computed property made accessible from the setup()

    <draggable v-model="myList" item-key="id" @start="drag=true" @end="drag=false" >
        <template #item="{card}">
            <p>{{ card }}</p>
        </template>
    </draggable>
import draggable from 'vuedraggable';

export default {
    name: "Dashboard",
    components: {
        draggable
    },
    setup() {
        const cards = computed(() => {
            return ['a', 'b', 'c']
        })
        return {
            cards
        }
    }
}

I know the template iterates through cards but no value is displayed or is neither accessible.


Solution

  • In Vue 3 - When setup is executed, the component instance has not been created yet. As a result, you will not have access to data, computed, methods component options.

    Reference: https://v3.vuejs.org/guide/composition-api-setup.html#accessing-component-properties

    Also in Draggable component, the array item will be accessed by element variable.

    Updated template code:

     <draggable v-model="myList" item-key="id" @start="drag=true" @end="drag=false" >
                <template #item="{element}">
                      <p>{{ element.value }}</p>
                </template>
        </draggable>
    

    Try changing the component code as follows,

    import draggable from 'vuedraggable';
    
    export default {
        name: "Dashboard",
        components: {
            draggable
        },
        data:function(){
         return {
           drag:false
         }
    
        },
        computed:{
          myList:function(){
              return [{id:1,value:'Card A'},{id:2, value:'Card B'}];
          }
        }
    }