Search code examples
javascriptvue.jsvuejs2vuexvue.draggable

VueJS: use computed "set/get" with Vue.Draggable and VueX


I'm seeking for a help with "Vue.Draggable". The second day I`m trying to update draggable array correctly.

The challenge is:

  • update draggable array using computed set/get functions
  • get draggable item properties including information about parent item and call axios function to update data on a MySQL.

Data sample:

{ cat1: { authors: [ { name: "Name 1" }, { name: "Name 2" } ] }, cat2: { authors: [ { name: "Name 3" }, { name: "Name 4" } ] } }

Rendering code:

<div v-for="(category, index) in categories">
    <draggable v-bind:id="index" v-model="category.authors" :options="{group:'authorslist', draggable:'.author'}" class="draggable-row" >
    <div v-for="author in category.authors" :key="author.id" class="author" >

What I'm trying to do:

Actually, mentioned construction works fine. But only visually. VueX gives an error about mutation process.

[Vue warn]: Error in callback for watcher "function () { return this._data.$$state }": "Error: [vuex] Do not mutate vuex store state outside mutation handlers." Error: [vuex] Do not mutate vuex store state outside mutation handlers.

Replacing v-model with :value helps but in this case, D&D is not working even visually.

I have tried a lot of variants... One is - create a computed property for "categories" and use "get/set" functions to call actions->mutations from them. The problem is - categories->set function is not working when we are changing authors array structure.

The second problem is drag and drop author between categories in such a way it allows us to get author and category id to use it in an Axios query.

I was trying to use @end event BUT(!) it works for only a sorting process but not for D&D between parent elements (categories).

I'll be very grateful for any help!


Solution

  • In order to avoid to directly mutate the store state, you should use a computed value and use store action. Something like:

    <draggable :id="index" v-model="authors" :options="{group:'authorslist', draggable:'.author'}">
    

    And:

    computed:{
     authors: {
            get() {
                return this.$store.state.authors
            },
            set(value) {
                this.$store.commit('updateAuthors', value)
            }
        }
    }