Push to vuex store array not working in VueJS

左心房为你撑大大i 提交于 2020-01-01 04:20:14

问题


I'm using Vuex to show a list of users from 'store.js'. That js file has array like this.

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

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

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

The above values are obtained from a URL (vue-resource). Below is the code to push the obtained data to the array. However, the data is not inserting

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

回答1:


You are trying to modify the vuex state from the vue component, You can not do it. You can only modify vuex store from a mutation

You can define a mutation like following:

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

Now you can commit this mutation from the vue instance, like following:

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


来源:https://stackoverflow.com/questions/41830731/push-to-vuex-store-array-not-working-in-vuejs

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