8
votes

When defining custom events Vue encourages us to define emitted events on the component via the emits option:

app.component('custom-form', {
  emits: ['inFocus', 'submit']
})

Using Vue 3's composition API, when a standalone composition function emits custom events, is it possible to define these in the composition function?

2

2 Answers

14
votes

No, because composition functions are used inside the setup hook which has not access to the other options like methods and emits :

export default defineComponent({
    name: "layout",
     emits: ['showsidebar']
    setup(props,{emit}) {
        const showSidebar = ref(true);
        const {
            breakpoints
        } = useBreakpoint();
        watch(breakpoints, (val) => {
            showSidebar.value = !(val.is === "xs" || val.is === "sm");
            emit('showsidebar',showSidebar.value )
        });
        return {
            showSidebar,
        };
    },
    data() {
        ...
    },

in the example above useBreakpoint offers only some logic that component could use it to behave, if there's some way to define that emits option in composition function, this function will always emit that event even if that function is used inside the component defines the handler of emitted event.

3
votes

I did it like this with the script setup syntax:

<script setup>
    import { defineEmit } from 'vue'
    
    const emit = defineEmit(['close'])
    
    const handleClose = () => {
        emit('close')
    }
</script>