vuex存储中未定义ReferenceError状态

时间:2018-10-16 18:27:09

标签: vue.js 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绑定/模板:

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

1 个答案:

答案 0 :(得分:2)

您在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
         }
       }
     });