javascript - ReferenceError 状态未在 vuex 存储中定义

标签 javascript vue.js vuejs2 vue-component vuex

我的 vuex 商店看起来像这样但是在调用 addCustomer 时我得到 ReferenceError: state is not defined:

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: { customers: [] },
  mutations: {
    addCustomer: function (customer) {
      state.customers.push(customer); // error is thrown here
    }
  }
});

这是 addCustomer 绑定(bind)/模板:

<template>
    <button class="button" @click="addCustomer">Add Customer</button>
</template>

这是 addCustomer 的定义:

<script>
  export default {
    name: "bootstrap",
    methods: {
      addCustomer: function() {
        const customer = {
          name: 'Some Name',
        };

        this.$store.commit('addCustomer', customer);
      }
    }
  }
</script>

最佳答案

您缺少 addCustomer 函数参数中的 state (addCustomer: function (customer)) :

     import Vue from 'vue';
     import Vuex from 'vuex';

     Vue.use(Vuex);

     export default new Vuex.Store({
       state: { customers: [] },
       mutations: {
         addCustomer: function (state,customer) {
           state.customers.push(customer); // error is thrown here
         }
       }
     });

关于javascript - ReferenceError 状态未在 vuex 存储中定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52841842/

相关文章:

javascript - 选择其他选择下拉菜单的选项

vue.js - 使用 Lodash 去抖 Vue 组件方法

来自字符串的 Javascript boolean 比较器

javascript - Node.js 文件安全

vue.js - Vue 命令行界面 3 : defined output paths

vue.js - Vue Cli 3 和 Firebase service worker 注册

javascript - 在 Vuejs 中从 child 到 parent 的事件监听

javascript - 提交按钮未被点击

javascript - 如何在 JS 中模拟 $(this)[0].files?

vue.js - Nuxt js - 在动态路由中传递对象参数