Search code examples
javascriptvue.jsvue-componentvuex

Pass value to vuex store from mapActions in component


How would I access the value inside my @click partSelect from my Vuex store.

Vue Template

<div id="currentPart">
    <img id="modelImg" @click="partSelect('modelOne')" class="modelImg" :src="model[0]"/>
    <img id="modelImg2" @click="partSelect('modelTwo')" class="modelImg" :src="model[1]"/>
    <img id="modelImg3" @click="partSelect('modelThree')" class="modelImg" :src="model[2]"/>
  </div>

Javascript to map actions

<script> 
 methods: mapActions([
    'getImage',
    'getImageAsync',
    'partSelect'
  ]),
</script>

Vuex Javascript

export const partSelect = ({ commit }) => commit('partSelect')

Solution

  • This is actually pretty simple, the action in Vuex should look like this:

    export const partSelect = ({ commit }, myString) => {
        // do something with myString
        commit('partSelectMutation') // execute the mutation
        // if the data should be added to the mutation:
        // commit('partSelectMutation', { myString })
    }
    

    to access the variable myString in the mutation (if the second version above was used):

    mutations: {
        partSelectMutation: (state, { myString }) => {
             state.myString = myString
        },
        //...
    }