Search code examples
vue.jsvuex

Call mapActions method from components script area


I know that I can call a mapActions method from the template of a component with only typing in the functions name. But how can I call a mapActions method from inside the script tag of a component.

axios.put('api/presenter/'+presenterId, presenter).then(function(res) {
                if(res.data !== true) {
                    // something went wrong
                    console.error(res.data)
                } else {
                    // here I want to call the mapActions method
                    callMethodHere(res.data)
                    alert('edited') // replace later
                }
          }).catch(function(err) {
              console.error(err)
          })

But callMethodHere will be undefined..

My vuex file

addSpeaker(state, speaker) {
    state.allSpeaker = [...state.allSpeaker, speaker]
}

addSpeaker({commit}, speaker) {
    commit('addSpeaker', speaker)
}

Here is my component where I call the vue store property:

<ul>
        <li v-for="presenter in allSpeaker" :key="presenter.id">
            {{presenter.name}} <button type="button" class="btn btn-primary" @click="edit(presenter.id)">Edit</button>
        </li>
    </ul>

computed: {
        ...mapState({
            allSpeaker: state => state.allSpeaker
        })
    },

Solution

  • Define the then callback as an arrow function to be able to get access to this (component instance) then call that method using this.callMethodHere(res.data) :

    axios.put('api/presenter/'+presenterId, presenter).then((res)=> {
                    if(res.data !== true) {
                        // something went wrong
                        console.error(res.data)
                    } else {
                        
                        this.callMethodHere(res.data)
                        alert('edited') // replace later
                    }
              }).catch(function(err) {
                  console.error(err)
              })