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

拥有回忆 提交于 2019-12-20 04:39:11

问题


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.


回答1:


try

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

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




回答2:


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:


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?



来源:https://stackoverflow.com/questions/52581488/how-can-i-clone-data-from-vuex-state-to-local-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!