Hi I am new to Vue and I wanted to ask a question about binding parent component value to a child component and when that value changes in the child I want to to change for the parent.
I made a JS Fiddle showing where I accomplish this but I am confused as to why it works the way it does. If I pass an Object to the prop it will bind the values, but if I pass them as is, I get the 'mutation' error.
JS:
var demo = new Vue({
el: '#demo',
data: {
Name: { firstName: "Bonjur", secondName: "Captain"},
firstName: "Hello",
secondName: "World",
}
});
Vue.component('working', {
template: '<div>' +
'First: <input v-model="names.firstName" />' +
'Second: <input v-model="names.secondName" /> ' +
'</div>',
props: {
names: null
}
})
Vue.component('broken', {
template: '<div>' +
'First: <input v-model="first" />' +
'Second: <input v-model="second" /> ' +
'</div>',
props: {
first: null,
second: null
}
})
HTML
<div id="demo">
<working :names="Name"></working>
<broken :first="firstName" :second="secondName" ></broken>
<p> {{Name.firstName}} {{Name.secondName}} </p>
<p> {{firstName}} {{secondName}} </p>
</div>
My original goal was to have the 'demo' Vue object be the main data object I was going to post back to the server, and have several components that edit specific parts of data in the main 'demo' object in their own unique way, so really just a separation of concerns.
Any comments/opinions/suggestions on designing an app this way using Vue are welcome.
I have also read that you can listen to the child's events and change the parent value that way.
How this sort of Child to Parent data binding was designed or intended to be done in Vue js v2.4?
Why does the above example works the way it does?
It working when you pass the object because in JavaScript:
Objects are passed by reference
Primitives are passed by value
you an checkout this to know about passed by reference and passed by value
When you pass the object as a prop and change it in the child component the passed object is mutated as only the memory location of the object is passed not a new object.
when you are passing the primitives as props you are creating a new copy and is received by child component.
That the reason when you change the value in the broken
component the newly copied value is changed not the original one in the root instance.
To make it work you should emit an event to parent component from child component . See custom events.
Its recommended to use events to mutate the props received from parent .
Here is the updated fiddle