javascript / intermediate
Snippet
Validating Custom Events with defineEmits
In intermediate Vue development, you should validate emitted events. By passing an object to defineEmits, you can define validator functions that check if the payload is correct before the event is sent to the parent component.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<script setup>const emit = defineEmits({submit: ({ email, password }) => {if (email && password.length > 8) {return true;}console.warn('Invalid submit payload!');return false;}});const handleSubmit = () => {};</script>
vue
Breakdown
1
submit: ({ email, password }) => { ... }
Validator function for the 'submit' event; returns false to trigger a console warning.
2
emit('submit', { ... });
Triggers the event with the provided object as payload.