我正在使用Vuex显示’store.js’的用户列表.那个js文件有这样的数组.
var store = new Vuex.Store({ state: { customers: [ { id: '1',name: 'user 1',},] } })
我想在同一个数组中插入一组新值
{ id: ‘1’,name: ‘user 1’,}
以上值是从URL(vue-resource)获得的.下面是将获得的数据推送到数组的代码.但是,数据未插入
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',}) }); }
解决方法
您正尝试从vue组件修改vuex状态,但您无法执行此操作.您只能从
mutation修改vuex商店
您可以定义如下的突变:
var store = new Vuex.Store({ state: { customers: [ { id: '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'}) }); }