In vue.js what is the right way to edit prop without changing parent data? What I mean by that is whenever we pass any property from parent to child in vue.js then if we mak
In your fiddle, the child component is using Object.assign()
to create a copy of data
, which is an array of objects. However, this only creates a shallow copy, so the array elements would still refer to the original instances, leading to the behavior you're seeing.
A few solutions to deep copy the array:
Use JSON.parse(JSON.stringify(this.data))
, which works reasonably well for objects of strings and numbers:
data() {
return {
local_data: JSON.parse(JSON.stringify(this.data))
}
}
(demo 1)
Map the objects into new ones:
data() {
return {
local_data: this.data.map(x => ({...x}))
}
}
(demo 2)
Use a utility library, such as lodash
's cloneDeep
data() {
return {
local_data: _.cloneDeep(this.data)
}
}
(demo 3)