I have made a component for my forms which I pass the main object as props to the component. For it’s items I pass a json including each form input’s data. In this data I pass the property name to integrate v-model to it’s corresponding data. Consider about the main object as :
**parent**: <custom-input :personInfo="personInfo" :items="items"> </custom-input>
**child**: <input v-model="personInfo[propertyName]"/>
items: [
{property: 'birth.date', ...}
]
personInfo : {
name: '',
birth: {
date: ''
}
}
So for date field I have to pass ‘birth.date’ as the v-model name to component which is giving error. How should I pass this deep object in parent and how to access it in child component?
Here is added a code sandbox: Codesandbox
Advertisement
Answer
first of all I see you are mutating a prop from the child component which is a bad practice as it is, so consider changing it to use v-model on the parent component or emit the property and value you want to change from the child to the parent.
As for question about ‘birth.date’ for example – you can not pass it to v-model because JavaScript doesn’t know to address this string as a deep object, so when you try to access parsedInfo['birth.date'] it looks for the matching string in the parsedInfo object, not as a deep object.
(if parsed info was: parsedInfo = { 'birth.date': '' } it would have find a value)
so I think the easiest way to achieve your goal is to use lodash _.set(obj, property) method, See: https://lodash.com/docs/4.17.15#set
if you want to use it with v-model you can use a computed property with get and set methods like so:
infoProperty: {
get: {
// return the info[property]
}
set: {
// use the _.set(obj, property) method
}
}