admin管理员组

文章数量:1317906

My vuex store looks like this but when calling addCustomer I get 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
    }
  }
});

This is the addCustomer binding/template:

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

This is the definition for addCustomer:

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

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

My vuex store looks like this but when calling addCustomer I get 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
    }
  }
});

This is the addCustomer binding/template:

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

This is the definition for addCustomer:

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

        this.$store.mit('addCustomer', customer);
      }
    }
  }
</script>
Share Improve this question edited Jul 18, 2020 at 9:56 Boussadjra Brahim 1 asked Oct 16, 2018 at 18:27 Alexander ZeitlerAlexander Zeitler 13.1k14 gold badges89 silver badges142 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

You're missing the state in addCustomer function parameters (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
         }
       }
     });

本文标签: javascriptReferenceError state is not defined in vuex storeStack Overflow