Kirk Ross
Kirk Ross

Reputation: 7163

Vuex - transform store object without altering original

I'm trying to copy a store object for local transformation but my alteration function is changing the original store object also. I'm using ...mapState["storeObject"]

This is basically what's happening:

state.storeOjb = "original value" 
this.local = storeOjb ;
this.local = "altered version of storeOjb"

storeOjb === "original value" // false -- why?

Upvotes: 0

Views: 171

Answers (2)

Stark Buttowski
Stark Buttowski

Reputation: 1849

I'm not sure exactly what's your problem is. But you can remove the object mutation by

this.local = Object.assign({}, storeObj)

Vue

In Vue JS, for local changes you can use computed property of the storeObj.

computed: {
  localValue: function() {
    return { ...storeObj, newChange: true }
  }
}

Upvotes: 1

Yu Leung
Yu Leung

Reputation: 15

It passed an object reference since your code this.local = storeOjb When you change the value of this.local, state.storeOjb also changed. So you may change your code like this.local = storeOjb + "", so we can only copy the value but not object reference.

Upvotes: 0

Related Questions