首页 > 解决方案 > 点击后的Vuex错误和操作

问题描述

我在 Vue JS 和 VueX 的项目中遇到问题。我们有一个 Modal 组件,它必须在单击按钮时打开或关闭。因此,我们在 Vue X 中充分了解了正确的模态模块:

  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

在触发动作的组件上,我们已经导入了 getter 和动作

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

在模板中:

        <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>

但是当我点击这个按钮时它不起作用,当我点击打开模式的按钮时,我得到了:

                    <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()"
                    >

我有这个错误信息:

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

当我点击 Fermer 按钮时,我有这个:

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

如果你有线索,我不明白为什么非常感谢你。

标签: vue.jsvuex

解决方案


您应该在将您的操作映射到方法时提供别名,以便防止名称冲突:

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

然后在您的模板中使用别名:

<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()"
 >

推荐阅读