Vue Composition API: Defining emits

Total
0
Shares

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?


Solution

No, because composition functions are used inside the setup hook which doesn’t have 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, useBreakpoint offers only some logic that the component could use. If there was a way to define the emits option in the composition function, then the function would always emit the event, even if the function is only used inside the component that defines the handler of the emitted event.

with the new script setup syntax you could do it as follows:

<script setup>
 import { defineEmits,watch,ref } from 'vue'
    
    const emit = defineEmits(['showsidebar'])
    const showSidebar = ref(true);
    const { breakpoints } = useBreakpoint();
    watch(breakpoints, (val) => {
            showSidebar.value = !(val.is === "xs" || val.is === "sm");
            emit('showsidebar',showSidebar.value);
        });
</script>

Source: StackOverflow.com

Leave a Reply

Your email address will not be published. Required fields are marked *