0

I have a child component that functions as an edit section. It copies a single prop on created() to serve as the v-model for editing, as I don't want any edits to reflect on the parent until the user clicks the save button. When the user clicks save, I $emit the edited model back to the parent to update. In theory.

In reality, the parent model seems to be reactive whenever I edit the child component, despite the child <input> supposedly acting on a copy of the passed prop. Why is this, and how do I prevent it?

<h2>{{ location.name }}</h2>
<edit-location v-if="editing" :location="location" />

EditLocation.vue:

<template>
  <input v-model="copyOfLocation.name">
  <button>Save</button>
</template>

<script>
export default {
  props: {
    location: {
      required: false,
      type: Object,
    },
  },
  data() {
    return {
      copyOfLocation: {},
    }
  },
  created() {
    this.copyOfLocation = this.location;
  },
}
</script>
Erich
  • 2,408
  • 18
  • 40
  • You're assigning the object to a new property but it's still the same object. Despite the name it isn't actually a copy. – skirtle Apr 15 '20 at 03:43

1 Answers1

2

While assigning the value of location to copyOfLocation, it actually assigns the reference. That make the issue. Try

this.copyOfLocation = JSON.stringify(JSON.parse(this.location));

while copying the value in the created hook. This will not copy the reference.

this.copyOfLocation = _.cloneDeep(this.location); // cloning using Lodash library.
Rijosh
  • 1,538
  • 1
  • 8
  • 11