Click on vuex storage array not working in VueJS

I use Vuex to show a list of users from "store.js". This js file has such an array.

var store = new Vuex.Store({
  state: {
    customers: [
      { id: '1', name: 'user 1',},
    ]
  }
})

I want to insert a new set of values ​​into the same array

{id: '1', name: 'user 1',}

The above values ​​are obtained from the URL (vue-resource). Below is the code for entering the received data into an array. However, data is not inserted

mounted: function() {
      this.$http.get('http://localhost/facebook-login/api/get_customers.php')
      .then(response => {
        return response.data;
      })
      .then(data => {
        store.state.customers.push(data) // not working!!
        console.log(data) // prints { id: '2', name: 'User 2',}
        store.state.customers.push({ id: '2', name: 'User 2',})
      });
    }
+4
source share
1 answer

You are trying to change the state of vuex from the vue component, you cannot do this. You can only change vuex repository from mutation

You can define a mutation as follows:

var store = new Vuex.Store({
  state: {
    customers: [
      { id: '1', name: 'user 1',},
    ]
  },
  mutations: {
     addCustomer (state, customer) {
      // mutate state
      state.customers.push(customer)
    }
  }
})

vue, , :

mounted: function() {
      this.$http.get('http://localhost/facebook-login/api/get_customers.php')
      .then(response => {
        return response.data;
      })
      .then(data => {
        store.commit('addCustomer', { id: '2', name: 'User 2'})
      });
    }
+11

Source: https://habr.com/ru/post/1667656/


All Articles