thatOneGuy
thatOneGuy

Reputation: 10642

How to commit mutations in a Vuex store, from a Vuetify list, VueJS

This follows on from my previous question : How to get states from a Vuex store from within a Vuetify list, VueJs

I understand how to get states from the store, but I am struggling commiting mutations from within a list.

Here is my list :

export default{
    name: 'menuList',
    data() {
        return {
            show: true,
            items: [{
                    title: 'Do something',
                    icon: 'web',
                    event: function () {
                        this.$store.commit('UI/DoSomething', {
                            argument1: "argument1",
                            rootStore: this.$store
                        })
                    }

                }
            ]
        }
    }
}

I have to have the event in a function as, if I don't, the commit will run straight away. I only want it to run when I click the button.

Here is my list creation :

<template>
  <v-navigation-drawer v-model="show" right clipped app fixed hide-overlay permanent="true">
    <v-list two-line>
      <template v-for="(item, index) in items">
        <v-list-tile :key="item.title" @click="item.event()">
          <v-list-tile-action>
            <v-icon>{{item.icon}}</v-icon>
          </v-list-tile-action>
          <v-list-tile-content>
            <v-list-tile-title v-html="item.title"></v-list-tile-title>
          </v-list-tile-content>
        </v-list-tile>
        <v-divider :key="index"></v-divider>
      </template>
    </v-list>
  </v-navigation-drawer>
</template>

When I wrap the commit with a function (so it doesn't execute automatically), the keyword 'this' refers to the object, not the Vue.

I'm sure I'm missing something simple here, any ideas ?

Upvotes: 0

Views: 1437

Answers (1)

Vamsi Krishna
Vamsi Krishna

Reputation: 31352

Why do you want to store a function to commit a mutation in the data option?You can just store the information needed to commit a mutation.

export default{
    name: 'menuList',
    data() {
        return {
            show: true,
            items: [{
                    title: 'Do something',
                    icon: 'web',
                    mutation: {
                        type: 'UI/DoSomething',
                         arguments:{ 
                            argument1: "argument1",
                            rootStore: this.$store
                        }
                        }
                    }

                }
            ]
        }
    }
} 

Then create a method as follows

commitMutation(mutation) {
     this.$store.commit(mutation.type, mutation.arguments)

}

Then add a click listener with item.mutation as an argument to commitMutation method.

@click="commitMutation(itrm.mutation)"

Upvotes: 1

Related Questions