Home > Mobile >  Passing data to child component also changes parent data
Passing data to child component also changes parent data

Time:06-23

Passing data from parent to child is a piece of cake and never had a problem that when you update the child prop data also updates the parent data at the same time, although now i want to avoid that.

I have this child component inside the parent component

    <address-dialog v-if="dialog.address.status" :countries="countries" :address-data="dialog.address.data" 
:open="dialog.address.status" @close="dialog.address.status = !dialog.address.status"></address-dialog>

Inside the child component i pass the props as is and then set them with the data method.

props: {
    open: {
        type: Boolean,
        default: false
    },
    addressData: {
        type: Object,
        default: null
    },
    countries: {
        type: Array,
        default: null
    }
},

data() {
    return {
        mdiClose,
        loading: false,
        valid: false,
        dialog: this.open,
        address: this.addressData,
        cities: [],
        states: [],
        overlay: false,
        snackbar: {
            status: false, 
            text: '',
            color: '#FF5252'
        },
        rules: {
            required: value => !!value || 'Required.',
        },
    }
},

When updating address inside the child component it also automatically updates the address in the parent component, how can i avoid that?

CodePudding user response:

Because they have the same reference ( as the address is an object ).

One solution is to pass a new object that has the addressData properties by spread operator.

address: { ...this.addressData }

CodePudding user response:

You should define the data properties bound to props as computed ones :

computed:{
   address(){
     return  this.addressData
   },
   dialog(){
    return this.open;
   }
}
  • Related