Why must defineEmits be used instead of emit directly? I feel that defineEmits is redundant or should be omitted?
What problem does this feature solve?
Why must defineEmits be used instead of emit directly? I feel that defineEmits is redundant or should be omitted?
now
const emit = defineEmits(['change'])
emit('change')
I feel that defineEmits is somewhat redundant. Is it possible to make defineEmits optional instead of mandatory? Is it feasible to provide an emit() function directly?
suggest
emit('change')
can use emit directly
What does the proposed API look like?
emit('change')
I thought about it again, why there are different views on defineProps and defineEmits, because defineProps defines objects, while defineEmits defines strings, and strings are used when using them, although there are also intelligent prompts.
But I still think it would be better if you can directly provide emit and use it directly
I feel that defineEmits is more of a programming normative limitation. It is useful for complex components, but it is a bit redundant for simple components. If I have only a few lines of code in a component and only one emit, I need to declare it. It seems a bit redundant if you can only use it. If you provide an emit method, you can let the developer choose whether to declare it before using it, or use it directly. It feels more friendly.
const useEmit = defineEmits([])
export default function emit(event, ...args) {
useEmit(event, ...args)
}
In normal (non-script-setup) components you need to use the emits:
option to declare which events will be emitted by the component.
This is important to that Vue can differentiate component event listeners from the parent from native event listeners, as the latter would be automatically applied to the root element. If you don't declare your events, you risk producing bugs as all of the events that you define as component events will also be added as native event listeners to the root element.
defineEmits()
is simply the script-setup version of that. We won't remove it and I don't see a good reason to actively provide a way around a feature that is kind of a necessary safeguard for your components to work reliably.