How can I clone data from Vuex state to local data

2020-03-27 10:33发布

How can I clone data from vuex state to local data attribute?

State

this.tsStore.shemes

Data Attribute

data () {
  return { shemes: [] }
}

I've tried do this in updated () this.shemes = this.tsStore.shemes but it's seems like it has a binding left.. because when i delete one item in this.shemes on click i've also delete that item in the state and get the error of "Do not mutate vuex store state outside mutation handlers".

I need to clone the state and do what ever I need to do with that data and on the same time don't affect my state state.

3条回答
叛逆
2楼-- · 2020-03-27 11:03
data(){
  return {
    shemes: null,
  }
},
beforeMount() {
  this.shemes = this.stateShemes
},
computed: {
  stateShemes() { return this.tsState.shemes }
  // OR that's how i do
  stateShemes() { return this.$store.getters['shemes'] }
}

UPDATE

So you get some value from your state by using computed variables. You cannot just assign the value from you store in the data() block. So you should do it beforeMount. That way if you have a watcher for shemes variable, it won't trigger on assigning computed value. If you put it in mounted() hook, the watcher will trigger.

Also, can you explain why do you use this call this.tsState.shemes instead of this.$store.getters.shemes?

查看更多
Juvenile、少年°
3楼-- · 2020-03-27 11:12

You need to create a new array. this.tsStore.shemes give you a reference to the bound array. You can try to use the spread operator or arr.slice() to create a new array with the same content. notice that this is a shallow copy.

this.shemes = [...this.tsStore.shemes]

or

this.shemes = this.tsStore.shemes.slice()
查看更多
手持菜刀,她持情操
4楼-- · 2020-03-27 11:25

try

this.shemes = JSON.parse ( JSON.stringify ( this.tsStore.shemes) )

This will clone all value and objects from the array in the store.

查看更多
登录 后发表回答