skip to Main Content

Object or array defaults must be returned from a factory function (source).

Example:

foobar: {
  type: Object,
  default() {
    return {}
  }
}

// OR

foobar: {
  type: Object,
  default: () => ({})
}

foobar will return an empty object {} by default.

But if you want to know if it is defined, it will always return "true". So you can do this instead:

foobar: {
  type: Object,
  default() {}
}

// OR

foobar: {
  type: Object,
  default: () => {}
}

foobar will return as undefined by default.

Is that last practice naughty?

2

Answers


  1. Chosen as BEST ANSWER

    As @EstusFlask comments; instead of it invoking an empty function (default: () => {} i.e. (() => {})()) that returns undefined, you might as well just assign the default as undefined or null like so:

    foobar: {
      type: Object,
      default: null
    }
    

    foobar will return as null by default.


  2. You can check an object for definition by counting its keys:

    Object.keys(foobar).length > 0 // true when it is filled
    

    Or by using JSON’s stringify method:

    JSON.stringify(foobar) !== '{}' // true when it is filled
    

    There are many other approaches to check for an object’s emptiness. The reference topic.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search