[Vuejs]-Pass value to vuex store from mapActions in component

1πŸ‘

βœ…

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
    },
    //...
}

1πŸ‘

Simple example with mapped action as event callback:

var store = new Vuex.Store({
  state: {
    content: 'Old content'
  },
  mutations: {
    updateContent (state, payload) {
      state.content = payload
    }
  },
  actions: {
    mapMe (context, payload) {
      context.commit('updateContent', payload)
    }
  }
})

new Vue ({
  el: '#app',
  store,
  computed: {
    content () {
      return this.$store.state.content
    }
  },
  methods: Vuex.mapActions({
    mappedAction: 'mapMe'
  })
})
<div id="app">
  {{ content }}<br>
  <button @click="mappedAction('New content')">Click</button>
</div>

<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vuex"></script>
πŸ‘€user6748331

0πŸ‘

This worked for me:

const mutations = {
    myrequest (state, id) {
        console.log("id:" + id);
    }
}    
const actions = {
    myrequest ({ commit }, id) {
        commit('myrequest', id)
    }
}
πŸ‘€DevonDahon

Leave a comment