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 { defineEmits } from 'vue'
const emit = defineEmits(['close'])
const handleClose = () => {
emit('close')
}
</script>