【问题标题】:Vuex commit commits only the last value of an array from a responseVuex commit 只提交响应中数组的最后一个值
【发布时间】: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


【解决方案1】:

https://vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats

Vuex 是 Vue 的一个插件,因此 Vuex 状态的反应性遵循与 Vue 中反应性属性相同的规则。在您的情况下,由于您更新的属性是一个对象数组,Vue 只检测数组大小的变化,而不是数组中每个项目的详细信息。所以如果你需要在视图层触发更新,你必须使用Vue.set来代替:

import Vue from 'vue'

...

fetchVotes(state, payload) {
  Vue.set(state, 'votes', payload)
},

如果您需要从数组中删除项目,请使用 Vue.delete 而不是 delete

【讨论】:

  • 这似乎不起作用。使用上述方法,vue devTools 中的投票状态现在为零,但让我看看上面的链接,我可以有办法解决。
猜你喜欢
  • 1970-01-01
  • 2020-11-15
  • 1970-01-01
  • 1970-01-01
  • 2021-12-18
  • 2019-03-29
  • 2017-12-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多