Home > Software engineering >  Clone prop object into new data object
Clone prop object into new data object

Time:11-28

Base structure of Vue components;

Users.Vue (parent component)
EditUserModal.vue (child component)

I have a data table of users, when the user selects a user, this data property gets updated with the selected user (inside Users.vue);

  selectedUser: {}

I have a modal component that takes the selected user in as a prop

<edit-user-modal :selected-user="selectedUser"></edit-user-modal>

The modal has a form that is updated with values based on the data sent in

How i want the form to act - i want the user to be able to edit the data on the form, the form will be pre filled based on the selected user

My problem - i want to clone the selected user prop into a new data object, so that when the user starts filling out the form, the cloned data object will get updated and not the prop

What ive tried

props: ['selectedUser'],
mounted() {
    if (!_.isEmpty(this.selectedUser)) {
        this.clonedUserObject = Object.assign({}, this.selectedUser)
    }
},
data() {
    return {
        clonedUserObject: {}
    }
},

Also

props: ['selectedUser'],
data() {
    return {
        clonedUserObject: Object.assign({}, this.selectedUser)
    }
},

Both times, the data property clonedUserObject has been empty when i select a user

CodePudding user response:

This is most likely due to the prop not being ready at the time that mounted runs. This can be determined by checking via debug tools or console.log that the prop is populated or not at that time.

In this case, the solution is to use a watcher. For example:

watch: {
  selectedUser: {
    // This will make sure it picks up your prop if it is set at the start,
    // allowing you to fully remove the mounted hook
    immediate: true,
    // If you need to check if a single internal property of the selectedUser changed
    // also set deep: true
    deep: true,
    handler: (val) {
      this.clonedUserObject = Object.assign({}, val);
    }
  }

}
  • Related