Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I clone data from Vuex state to local data?

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.

like image 549
nahoj Avatar asked Sep 30 '18 19:09

nahoj


2 Answers

Using cloneDeep is still the best way to go, here is an example

<script>
import { cloneDeep } from 'lodash-es'

...
const properlyClonedObject = cloneDeep(myDeeplyNestedObject)
...
</script>

It's bullet proof, battle-tested and is also a tree-shakable function.

If you need this for Nuxt, here is how to achieve this.

like image 157
kissu Avatar answered Oct 21 '22 20:10

kissu


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()
like image 25
elad frizi Avatar answered Oct 21 '22 19:10

elad frizi