Skip to content

Generate default prop value based on value of another prop #6358

@riophae

Description

@riophae

What problem does this feature solve?

I have been recently making a Vue component library which has a dozen of props. There are two props called showCount and showCountOnSearch respectively. The props property of my component looks like:

export default {
  props: {
    showCount: {
      type: Boolean,
      default: false,
    },
    showCountOnSearch: {
      type: Boolean,
      default: false,
    },
    // ...other props
  },
  // ...
}

I want the default value of showCountOnSearch to be determined based on the value of showCount. For example:

  • When showCount is not specified, set showCount to the default value false. If showCountOnSearch is not specified either, set it to false too.
  • When showCount is specified and showCountOnSearch is not, set showCountOnSearch to the same value of showCount.

In other words, showCountOnSearch always defaults to the value of showCount.

What does the proposed API look like?

Currently Vue allows default property to be functions to generate default value dynamically. However, seems it's impossible to obtain another prop's value inside the default function.

I hope the API to look like:

export default {
  props: {
    showCount: {
      type: Boolean,
      default: false,
    },
    showCountOnSearch: {
      type: Boolean,
      default(props) {
        return props.showCount
      },
    },
    // ...other props
  },
  // ...
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions