Vue Tip: Validate Events and Prop Types
Michael Hoffmann
@mokkapps
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:
<script setup>
defineProps({
type: {
type: String,
default: 'success',
validator(value) {
// The value must match one of these strings
return ['success', 'warning', 'danger'].includes(value)
},
},
})
</script>
Let's pass an invalid type to the component:
<template>
<Component type="invalid" />
</template>
Vue will produce a console warning (if using the development build):
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:
<script setup>
const emit = defineEmits({
// No validation
click: null,
// Validate update event
update: (value) => {
if (value) {
return true
} else {
console.warn('Invalid value event payload!')
return false
}
},
})
</script>
<template>
<button @click="$emit('update')">Update</button>
</template>
StackBlitz Example
You can try it yourself in the following StackBlitz project:
If you liked this Vue tip, follow me on BlueSky to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter :
Nuxt Tip: Render Component Only on Client-Side
Nuxt Tip: Refresh Data by Watching Sources Using useAsyncData