0

I have a function inside the methods property which takes passedData value from the data() method, does some changes to the object and stores the new value in a constant

this somehow causes a side effect which changes the passedData value also. What is the cause and how can I prevent that ?

this.passedData: -->

{"propss":"value"}
App.vue?3dfd:61 {"propss":"propss : value"}
App.vue?3dfd:49 {"propss":"propss : value"}
App.vue?3dfd:61 {"propss":"propss : propss : value"}

new Vue({
  el: "#app",
  
 

  data() {
    return {
      passedData: { propss: "value" },
    };
  },

  methods: {
    displayData() {
      console.log(JSON.stringify(this.passedData));
      
       const root = d3.hierarchy(this.passedData, function(d) {
    if(typeof d == "object")
     return Object.keys(d).filter(d=>d!="$name").map(k=>{
       if(typeof d[k] == "object") d[k].$name = k;
       else d[k] = k + " : " + d[k];
       return d[k];
     }); 
    
  })
      
       console.log(JSON.stringify(this.passedData));
      
    },
  },
  
  
  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
 <button type="button" @click="displayData">display</button>

 
</div>
Sator
  • 636
  • 4
  • 13
  • 34

1 Answers1

0

The problem you are facing here is, that data in vue.js is reactive. So changing data stored anywhere will change the source of the data too.

If you want to change something without facing issues due to reactivity, you need to assign this data without reference as you need. Small example:

// Passing your reactive data
passedData: { propss: "value" },
newData: {}

// Passing data to new property and reactivity
this.newData = this.passedData

this.newData.propss = 'newValue' // this will change passedData.propss to "newValue" too

// Assign Data without reference
this.newData = JSON.parse(JSON.stringify(this.passedData))

If you now change newData it wont affect passedData, as JSON.parse(JSON.stringify(this.passedData)) created a new state without reference to the original.

Note that this should only be a workaround, it isn´t a proper state management.

StevenSiebert
  • 1,306
  • 4
  • 15
  • 26