2

i can't understand what the ... want this vue! please help if you can! this is my code

var groupadding = new Vue({
el: '#groupAdd',
data:{
     currentFullData: [],
     localData: []
   },
   methods: {
     getDepartment() {
       var sendData = id; // this is example
       this.$http.post('some api ', sendData, {emulateJSON: true})
       .then( resp => {
         this.currentFullData = resp.data;    
       }
     },
     getLocalDepartment() {
     this.localData = this.currentFullData;
     }
   }
})

in currentFullData for example i have 4 boolean field, 'create' , 'read', 'update', 'delete'

this 4 fields gets localData too, but when i change in localData some of them, they changes in currentFullData too!!!!!!!!!!!!!!!

soooooo anyone can explain me wtf is this?!?!?!

Jorjini
  • 25
  • 4

2 Answers2

2

This is because you are actually modifying the same object (as you wrote this.localData = this.currentFullData;)

If you want to initialize this.localData using currentFullData, you need to copy it :

this.localData = Object.assign({}, this.currentFullData);

see https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

reinarg
  • 446
  • 5
  • 6
  • Oh nvm, I didn't see it was an array and not an object, see anchal20 answer for cloning and array. – reinarg Aug 30 '17 at 12:03
  • sorry for my answer, you was right this.currentFullData = cloneArray(this.currentFullData, data); function cloneArray($name, $array) { return $name = JSON.parse(JSON.stringify($array)); } this WOOOOOOOOOOOOOOOOOORKS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! thank YOU!!!! – Jorjini Aug 30 '17 at 12:23
1

Thanks for the question. The issue is not with vue and the data values 'currentFullData' and 'localData'. As your data variables are Arrays, therefore when you assign the value like this this.localData = this.currentFullData then this.localData is a pointer to this.currentFullData. So, when you change localData then currentFullData also changes. Thus, to avoid this, pass a reference of this.currentFullData to this.localData like this this.localData = this.currentFullData.slice()

For more understanding you can refer this question about arrays on stackoverflow

anchal20
  • 171
  • 1
  • 5
  • Uncaught (in promise) TypeError: this.currentFullData.slice is not a function – Jorjini Aug 30 '17 at 12:21
  • You can check my codepen https://codepen.io/anchal20/pen/QMzQQG and also the link I shared above. I hope you are typing it correctly, it should be this.currentFullData.slice() and the resp.data should be of array type. – anchal20 Aug 31 '17 at 08:50