Skip to content

Pass nested object name as props to component

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: '', ...}

personInfo : {
    name: '',
    birth: {
        date: ''

So for date field I have to pass ‘’ 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



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 ‘’ 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[''] it looks for the matching string in the parsedInfo object, not as a deep object.

(if parsed info was: parsedInfo = { '': '' } 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:

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