最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - vue how set default props for nested object - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question edited Jul 17, 2020 at 16:30 Boussadjra Brahim 1 asked Nov 4, 2018 at 17:53 angry kiwiangry kiwi 11.4k28 gold badges123 silver badges167 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 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: ''
              }
           } 
        }
    }
},

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: ''
                        }
                     }
            }
         }
发布评论

评论列表(0)

  1. 暂无评论