Second2None
Second2None

Reputation: 1600

Vue2 Variable unexpected behaviour

I'm having some issues with Vue2 variables.

My aim is to create a backup of a variable pulled down from an Axios call, this will then be used to reset the main variable back to the original values. The main variable is called loaded_data, and the copy is called original_data.

My issue is that when I copy the variable over, it's passing it by reference, not value. So when I update my loaded_data variable, the original_data

How the variables are defined:

data() {
    return {
      loaded_data: false,
      original_data: false,
    };
},

How the variables are set:

this.loaded_data = axios_response.response.data;
this.original_data = axios_response.response.data;

Reset data function.

reset_data() {
    console.log('ORIGINAL', this.original_data);
    console.log('LOADED', this.loaded_data);

    this.loaded_data = this.original_data;
},

So when I update my loaded_data variable. eg:

loaded_data.value = 'this is an update to the data';

It's also updating the original_data variable. Console log looks like this if I run the reset_data() function.

ORIGINAL {__ob__: Observer}
value: "this is an update to the data"

LOADED {__ob__: Observer}
value: "this is an update to the data"

What it should look like:

ORIGINAL {__ob__: Observer}
value: ""

LOADED {__ob__: Observer}
value: "this is an update to the data"

It doesn't really make sense because loaded_data and original_data aren't linked beside the reset_data function and setting it with axios_response.

Any help or ideas would be greatly helpful.

Upvotes: 1

Views: 32

Answers (1)

FrankPl
FrankPl

Reputation: 929

JavaScript copies the same object into both variables. You would need a second copy of your object as original_data. One way to get that is to use

this.original_data = JSON.parse(JSON.stringify(axios_response.response.data));

after you got the data.

Upvotes: 1

Related Questions