ReferenceError state is not defined in vuex store

☆樱花仙子☆ 提交于 2020-04-14 14:27:31

问题


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.commit('addCustomer', customer);
      }
    }
  }
</script>

回答1:


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


来源:https://stackoverflow.com/questions/52841842/referenceerror-state-is-not-defined-in-vuex-store

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!