2

I want to pass array from one component to the other in vueJs, which i am able to do with

<add-new-admin-modal
 :permissions = "permissions"
</add-new-admin-modal>

In my other component which is a modal actually, I am receiving the props as,

props: {
  permissions: {
    type: Array,
    default: () => []
  }
}

Here when i try to change the permissions array, it reflects the parent data, As mentioned in the documentation.

https://v2.vuejs.org/v2/guide/components-props.html#One-Way-Data-Flow

so i tried with spread operator

data () {
 return {
  statePermissions: [...this.permissions]
 }
}

The statePermissions array is still empty when i try above method,

I even tried with Object.assign

data () {
 return {
  statePermissions: Object.assign([], this.permissions)
 }
}

Still it doesn't work.

In my Modal, I am accessing it as

<div v-for = "permission in statePermissions" :key = "permission.id">
 ...someHtml here.
</div>

The main idea is, I have a component which gets the data through an api, then i have a modal which takes this data and updates it accordingly and submit it to an api. when the modal is closed, the parent component should need to have the unedited data, so that if modal is reopened it should get unedited data.

In the process of using Modal, My parent component remains in the same state (It neither gets mounted nor changed), so their is no point in making the request for default data again from parent.

tony19
  • 125,647
  • 18
  • 229
  • 307

2 Answers2

0

Your problem is probably that the default value for you prop is an empty array and you're assigning it to a local variable before the property is properly populated by the parent (or it might even be a lifecycle issue).

Try moving your assignment to the local variable to the mounted() hook or even better if you wan't it to be reactive watch your property:

watch: {
  permissions(newValue) {
    this.statePermissions = newValue
  }
}

You also don't need to ...spread an array to assign it to an array.

TommyF
  • 6,660
  • 8
  • 37
  • 61
0

Since permissions is an array of objects, when you make a copy of it, the resulting array is a shallow copy meaning it will contain the same references to objects. That's why modifying the new array's values update the old array's values as well. You need to create copies of the objects inside permissions.

If permissions only contains primitives, you can do something like this:

this.statePermissions = JSON.parse(JSON.stringify(this.permissions));

If permissions is of a certain type (i.e. new Permission()), you can map it (I think this is cleaner):

this.statePermissions = this.permissions.map(x => new Permission(x.propA, x.propB, etc.));

This way, each cloned object in statePermissions will have the same properties as the object it's copied from in permissions, but it's independent so modifications won't affect the parent it was created from.

There's a few other ways in this post.

Nick G
  • 1,953
  • 12
  • 16