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

javascript - How to clone a Vuex array? - Stack Overflow

programmeradmin3浏览0评论

I have a Vuex array (this.buildings). I can't mutate it directly before turning it into a payload for an api, so I tried to clone it with slice():

const buildingsPayload = this.buildings.slice() 
  buildingsPayload.forEach((building, index) => {
  building.index = index
})

However I'm still getting the Do not mutate vuex store state outside mutation handlers. error.

What's the correct way of doing this?

I have a Vuex array (this.buildings). I can't mutate it directly before turning it into a payload for an api, so I tried to clone it with slice():

const buildingsPayload = this.buildings.slice() 
  buildingsPayload.forEach((building, index) => {
  building.index = index
})

However I'm still getting the Do not mutate vuex store state outside mutation handlers. error.

What's the correct way of doing this?

Share Improve this question asked Jun 30, 2017 at 3:04 alexalex 7,61115 gold badges53 silver badges80 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

Try something like this:

const buildingsPayload = this.buildings.map((b, idx) => Object.assign({ index: idx }, b));

It will also copy the objects, so you're not modifying the state of those.

发布评论

评论列表(0)

  1. 暂无评论