Vue Tip: Validate Events and Prop Types
You can validate prop types and events in Vue. If a requirement is not met, Vue will warn you in the browser's JavaScript console.
Such validations are typically used if your component is intended to be used by others.
Prop Type Validation
In <script setup>
, only the function argument of defineProps()
supports custom validator functions (as of Vue 3.2.31).
To specify a prop validation function, you can provide an object with validation requirements to the defineProps()
macro:
Let's pass an invalid type to the component:
Vue will produce a console warning (if using the development build):
Vue Warn
Invalid prop: custom validator check failed for prop "type"
Events Validation
It's also possible to validate an emitted event.
You need to assign a function that receives the emit call's arguments. The function returns a boolean to indicate whether the event is valid or not:
StackBlitz Example
You can try it yourself in the following StackBlitz project:
If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Nuxt Tip: Refresh Data by Watching Sources Using useAsyncData
Nuxt 3's useAsyncData() composable can be used within your pages, components, and plugins to get access to data that resolves asynchronously. It can also be used to refresh the data loaded from the API based on the user's action. (pagination, filtering results, searching, etc.)
Nuxt Tip: Render Component Only on Client-Side
By default, Nuxt uses universal (client-side + server-side) rendering to render your application. The ClientOnly component can be used torender its slot only in client-side.