Alexandre Viretti
Alexandre Viretti

Reputation: 119

Vuex error and action following the click

I am having a problem on a project in Vue JS and VueX. We have a Modal component which must open or close upon the click of a button. We have therefore well informed in Vue X the correct modal module:

  namespaced: true,
  state : {
    show: false
  },
  // Getter functions
  getters : {
    showModal( state ) {
      return state.show
    }
  },
  actions : {
    showModal({commit}){
      commit('SHOWMODAL');
    }
  },
  // Mutations
  mutations : {
    SHOWMODAL(state) {
      state.show = !state.show
    }
  }
}
export default ModalModule;// export the module

On the component that triggers the action, we have imported the getters and the actions

<script>
import { mapGetters, mapActions } from 'vuex';
export default {
  data() {
    return {
    };
  },
  computed: {
    ...mapGetters('ModalModule', [
        'showModal',
    ])
  },
  components: {
  },
  methods: {
    ...mapActions('ModalModule', [
        'showModal',
    ]),
  }
};
</script>

And in the template :

        <button
          class="bg-green-500 text-white active:bg-green-600 font-bold uppercase text-xs px-4 py-2 rounded shadow hover:shadow-md outline-none focus:outline-none mr-1 ease-linear transition-all duration-150"
          type="button"
          @click="showModal()"
        >
          FERMER
        </button>

But when i click on this button it doesn't work and when i click on the button which open the modal i've got :

                    <button
                      class="bg-green-500 active:bg-green-600 uppercase text-white font-bold hover:shadow-md shadow text-xs px-4 py-2 rounded outline-none focus:outline-none sm:mr-2 mb-1 ease-linear transition-all duration-150"
                      type="button"
                      @click="showModal()"
                    >

I've this error message :

Computed property "showModal" was assigned to but it has no setter.

And when i click on Fermer button i've this :

Error in v-on handler: "TypeError: _vm.showModal is not a function"

i don't understand why thank you very much if you've got a clue.

Upvotes: 1

Views: 150

Answers (1)

Eldar
Eldar

Reputation: 10790

You should give an alias while mapping your action into methods so you can prevent name collision:

methods: {
...mapActions('ModalModule', {
    'toggleShowModal' : 'showModal',
}),

And then in your template use the alias :

<button class="bg-green-500 active:bg-green-600 uppercase text-white font-bold hover:shadow-md shadow text-xs px-4 py-2 rounded outline-none focus:outline-none sm:mr-2 mb-1 ease-linear transition-all duration-150"
  type="button"
  @click="toggleShowModal()"
 >

Upvotes: 1

Related Questions