Subscribe on changes!

Allow defineEmits inside composable function

avatar
Sep 16th 2022

What problem does this feature solve?

I want to extract some logic out of multiple child components, but that logic includes emitting event(s) to the parent element, as part of a dynamic layout component mechanism:

<script setup>
    import { onBeforeMount } from 'vue';
    import MyLayout from './MyLayout.vue';

    const emit = defineEmits(['update:layout']);
    onBeforeMount(() => {
        emit('update:layout', MyLayout);
    });
</script>

But Vue specifically stops me doing this because defineEmits can't be used inside composable functions. I don't want to have to duplicate the defineEmits declaration across all my child components, that defeats the purpose of extracting stuff into a function.

What does the proposed API look like?

Allow me to import defineEmits the same way as composable API functions are imported, so they can be used in user-created composable functions:

import { onBeforeMount, defineEmits } from 'vue';

export function useLayout(layout) {
    const emit = defineEmits(['update:layout']);
    onBeforeMount(() => {
        emit('update:layout', layout);
    });
}
avatar
Sep 17th 2022

duplicate of #6400