Javascript 推送到 vuex 存储数组在 VueJS 中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41830731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Push to vuex store array not working in VueJS
提问by Gijo Varghese
I'm using Vuex to show a list of users from 'store.js'. That js file has array like this.
我正在使用 Vuex 显示来自“store.js”的用户列表。那个 js 文件有这样的数组。
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',}
{ 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
上述值是从一个 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', name: 'User 2',})
});
}
回答by Saurabh
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
您正在尝试从 vue 组件修改 vuex 状态,您不能这样做。您只能从突变修改 vuex 存储
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:
现在您可以从 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'})
});
}

