Vue Composition API: Defining emits Vue Composition API: Defining emits vue.js vue.js

Vue Composition API: Defining emits


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, useBreakpoint offers only some logic that the component could use. If there's some way to define that emits option in the composition function then this function will always emit that event even if that function is used inside the component that defines the handler of emitted event.


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>


if you want to get all the context

setup(props, context) {   // console.log(context)   context.emit("update:modelValue", data)},