Search code examples
javascriptvuejs2vue-componentjavascript-objectsemit

VueJS - Auto bind parent object in child component with emit, why?


It's a bit hard to telling this scenario. But I'll try.

I have an child component. This component will send an object to parent with $emit

this.$emit("get-condition", this.sendData);

This is sendData structure of sending in $emit. This data structure bind with v-model directive in form elements.

sendData: {
           selectedValue: null,
           cond: null,
           inTime: null,
           operand: null,
           inTimeValue: null,
           compareValue: null
 }

In parent, I have an empty object and assign the data into this object.

setCondition(obj) {

   this.$set(this.mockConditions, this.mockKey++ , obj);
},

After that I have an object like this in parent. I mean I pass the data from child to parent. It's ok right now.

0: Object {
    compareValue:"25"
    cond:"Average"
    inTime:null
    inTimeValue:"23"
    operand:null
    selectedValue:"Flow"
}

At this point in child form binding with parent object. If open child form and enter some new values to form elements, it affected in parent object with created $emit event.

How to seperate them after $emit event ?


Solution

  • The obj parameter passed to setConditionmethod is a reference to sendData attribute. To unbind that reference you can clone the object before emitting it:

    this.$emit("get-condition", JSON.parse(JSON.stringify(this.sendData)));