推送到Vuex存储阵列在VueJS中不起作用 [英] Push to vuex store array not working in VueJS
问题描述
我正在使用Vuex来显示"store.js"中的用户列表.该js文件具有这样的数组.
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',名称:'user 1',}
{ id: '1', name: 'user 1',}
以上值是从URL(vue资源)获得的.下面是将获得的数据推送到数组的代码.但是,数据未插入
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',})
});
}
推荐答案
您正试图通过vue组件修改vuex状态,但是您不能这样做.您只能通过变异
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)
}
}
})
现在您可以从vue实例中进行此突变,如下所示:
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'})
});
}
这篇关于推送到Vuex存储阵列在VueJS中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!