最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Mutating Arrays Vuex - Stack Overflow

programmeradmin2浏览0评论

The following mutation does not work:

const mutations = {
  [types.UPDATE_IMG_URLS] (state, newArray) {
    state.imageUrlArray.concat(newArray)
  },
(...)
}

However this one does:

const mutations = {
  [types.UPDATE_IMG_URLS] (state, newArray) {
    state.imageUrlArray = state.imageUrlArray.concat(newArray)
  },
(...)
}

I thought arrays and objects were passed by reference in Javascript. Does Vuex meddle with this behavior?

The following mutation does not work:

const mutations = {
  [types.UPDATE_IMG_URLS] (state, newArray) {
    state.imageUrlArray.concat(newArray)
  },
(...)
}

However this one does:

const mutations = {
  [types.UPDATE_IMG_URLS] (state, newArray) {
    state.imageUrlArray = state.imageUrlArray.concat(newArray)
  },
(...)
}

I thought arrays and objects were passed by reference in Javascript. Does Vuex meddle with this behavior?

Share Improve this question edited Jan 26, 2017 at 19:27 softcode asked Jan 26, 2017 at 19:21 softcodesoftcode 4,68812 gold badges44 silver badges69 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

The concat method does not change the existing array, but returns a new array. That's why you need to actively overwrite state.imageUrlArray with the freshly returned array.

If, for some reason, you want to make the mutation in place, you should be able to to this: state.imageUrlArray(state.imageUrlArray, newArray)

See https://developer.mozilla/en/docs/Web/JavaScript/Reference/Global_Objects/Array/concat for more details.

发布评论

评论列表(0)

  1. 暂无评论