Categories
Vue Answers

How to set default values for Vue component props and how to check if a user did not set the prop?

Spread the love

Sometimes, we want to set default values for Vue component props and how to check if a user did not set the prop.

In this article, we’ll look at how to set default values for Vue component props and how to check if a user did not set the prop.

How to set default values for Vue component props and how to check if a user did not set the prop?

To set default values for Vue component props and how to check if a user did not set the prop, we can set the default property of the prop.

For instance, we write

export default {
  //...
  props: {
    year: {
      default: 2022,
      type: Number,
    },
  },
  //...
};

to add the year prop to the component.

We set its default value to 2022.

And we set its type to Number.

If year is 2022, then we know the prop isn’t set or it’s set to 2022.

Conclusion

To set default values for Vue component props and how to check if a user did not set the prop, we can set the default property of the prop.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *