【发布时间】:2019-06-13 12:25:14
【问题描述】:
我正在使用 vuex 开发 Laravel vue.js 项目,但在提交对商店的响应时遇到问题。我可以成功地从后端获取数组数据,但是当我提交响应时,存储只有数组的最后一个值被映射到状态,导致迭代时结果不正确。但是当我在组件中本地管理状态时,它可以正常工作。这是我的控制台窗口中的示例响应:
[{…}]
0: {id: 4, auth_id: 3, user_id: 3, power_id: 3, created_at: "2019-01-19
12:49:15", …}
length: 1
__proto__: Array(0)
app.js:90087
(2) [{…}, {…}]
0: {id: 1, auth_id: 2, user_id: 2, power_id: 1, created_at: "2019-01-19
12:03:52", …}
1: {id: 5, auth_id: 3, user_id: 2, power_id: 1, created_at: "2019-01-19
12:50:02", …}
length: 2
__proto__: Array(0)
app.js:90087
[{…}]
0: {id: 2, auth_id: 2, user_id: 2, power_id: 2, created_at: "2019-01-19
12:06:55", …}
length: 1
__proto__: Array(0)
app.js:90087
(2) [{…}, {…}]
0: {id: 3, auth_id: 3, user_id: 3, power_id: 2, created_at: "2019-01-19
12:46:48", …}
1: {id: 6, auth_id: 3, user_id: 3, power_id: 2, created_at: "2019-01-19
12:50:22", …}
length: 2
__proto__: Array(0)
这是我获取它并进行提交的方式:
fetchVotes() {
axios.get('/api/superpowers/fetchVotes/' + this.powerId + '/'
this.userId)
.then(response => {
console.log(response.data);
this.$store.commit('fetchVotes', response.data);
})
.catch(error => { console.log(error) });
},
然后在存储突变但只有数组的最后一个值被映射到状态投票:
fetchVotes(state, payload) {
state.votes = payload
},
但是当我在本地管理状态时,它可以工作:
fetchVotes() {
axios.get('/api/superpowers/fetchVotes/' + this.powerId + '/' +
this.userId)
.then(response => {
console.log(response.data);
this.votes = response.data
})
.catch(error => { console.log(error) })
},
请注意,fetchVotes 方法是在 forEach 循环中调用的。任何帮助将不胜感激。
【问题讨论】:
-
你怎么知道提交只映射最后一项?
-
@BoussadjraBrahim 在我的 vue 模板和 vue 开发工具中触发了结果。但它并不是真正的最后一项。每次我得到与上一个不同的值。
标签: javascript arrays loops vue.js vuex