【问题标题】:Vuex error and action following the click点击后的Vuex错误和操作
【发布时间】:2021-02-18 00:29:33
【问题描述】:

我在 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"

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

【问题讨论】:

  • 计算属性和方法具有相同的名称,这就是您收到该错误的原因。
  • 您的问题是您不能同时将操作和方法映射到同名showMethod。当您在模板中调用 showMethod 时,它实际上是在尝试设置一个值(因为您有一个同名的 getter)。

标签: vue.js vuex


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2013-04-12
    • 2017-12-26
    • 1970-01-01
    • 2021-07-21
    • 2018-03-13
    • 2014-12-30
    • 2019-06-20
    • 1970-01-01
    • 2022-01-23
    相关资源
    最近更新 更多