props:{
variants:{
type: Array,
default: []
}
options:{
type: Array,
default: []
},
},
data(){
return{
item:{
quantity: 1,
options: this.options,
},
}
},
I have a problem with this code: When i change item.options
value also options
get changed because as i understand, i am just assigning a reference to options
.
How to create a new object for item.options
instead of assigning a reference to the existing object in Vue3 Option Api
.
I tried {...this.options}
but it didnt work.
>Solution :
If it’s an array of primitives, shallow cloning is enough to achieve the desired result:
item:{
quantity: 1,
options: [...this.options],
}
Otherwise, you will need to perform deep cloning for which there are multiple ways to achieve it, you can search for it however using JSON.parse(JSON.stringify({}))
isn’t recommended.