How to tell whether a prop has been explicitly passed in to a component in Vue 3

Viewed 362

Is there any way to tell, from within a Vue 3 component, what props are being explicitly passed in (i.e., as attributes on the component's tag in the parent template)—as opposed to being unset and receiving their value from a default?

In other words, if I have a prop declared with a default value, like this:

props: {
  name: {
    type: String,
    default: 'Friend'
  }
}

How can I tell the difference between this:

<Greeting name="Friend" />

and this:

<Greeting />   <!-- name defaults to 'Friend' -->

In both instances, the component's name prop will have the same value, in the first case being passed in explicitly and in the second case being assigned the default.

Is there a systematic way in Vue 3 to determine the difference?

In Vue 2 you could use this.$options.propsData for this purpose—it contained only the properties that were directly passed in. However, it has been removed in Vue 3.

1 Answers

This information may be available in component instance with getCurrentInstance low level API, but there is no documented way to distinguish default and specified prop value that are === equal.

If default prop value is supposed to differ from the same value that was specified explicitly, this means that this isn't the case for default prop value, and it should be specified in some other way, e.g. through a computed:

const name = computed(() => {
 if (props.name == null) {
   console.log('default');
   return 'Friend';
 } else
   return props.name;
});
Related