8
votes

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

3 Answers

19
votes

try

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

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

5
votes

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()
3
votes
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?