在 vuex 存储中未定义 ReferenceError 状态

Ale*_*ler 3 javascript vue.js vue-component vuex vuejs2

我的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
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

这是addCustomer绑定/模板:

<template>
    <button class="button" @click="addCustomer">Add Customer</button>
</template>
Run Code Online (Sandbox Code Playgroud)

这是 的定义addCustomer

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

        this.$store.commit('addCustomer', customer);
      }
    }
  }
</script>
Run Code Online (Sandbox Code Playgroud)

Bou*_*him 6

您缺少stateaddCustomer 函数参数 ( 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
         }
       }
     });
Run Code Online (Sandbox Code Playgroud)