7

my props is like this

house = {
  kitchen:{
    sink: ''
  }
}

I tried something like this, didnt work.

props: {
    house: {
        type: Object,
        default: () => {
            kitchen : {
                sink: ''
            }
        }
    }
},

How to set default props for such object?

0

2 Answers 2

17

From the docs:

Object or array defaults must be returned from a factory function

So the problem is that you are not returning the default object.So you can either do:

props: {
    house: {
        type: Object,
        default: () => ({ // <= note the parenthesis
            kitchen : {
                sink: ''
            }
        }) // <= here also
    }
},

Or

props: {
    house: {
        type: Object,
        default: () => {
           return  {
              kitchen : { // <= note the return
                sink: ''
              }
           } 
        }
    }
},
Sign up to request clarification or add additional context in comments.

Comments

9

The following solution should work :

  props: {
   house: {
       type: Object,
        default: () => ({
          kitchen: {
             sink:''
            }
       })
  },
 }

check this codesandbox

if the above solution doesn't work, you could use a normalized computed property :

     props: {
         house: { type: Object }
       },
    computed: {
           normalizedHouse() {
              return {
                      kitchen:{
                         sink: ''
                        }
                     }
            }
         }

3 Comments

Is it possible to set an object with 2 values: kitchen: { sink: 'yes', windows: 3 } And when using the <component :kitchen={sink: 'no'}/> and then the last default option windows get 3 as default? i don't seem to be able to do this default behavior like that with nested objects and default values
Yes, of course !
I've posted my problem here: stackoverflow.com/questions/72992210/… Hope you can see what I'm doing wrong

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.