Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the focus event fired twice from a Vue 3 child component?

When I fire a focus event from a top level input field in Vue 3:

<input @focus="$emit('focus')">

…the event is fired once when the input field is focused (as I would expect).

However, when you put this same input field into a child component and focus it:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<InputField @focus="$emit('focus')" />

…the event is fired twice.

See https://stackblitz.com/edit/vue-wjhche?devToolsHeight=33&file=src/components/HelloWorld.vue

Can you please help me to understand why this is happening? Thanks!

>Solution :

So, you shouldn’t put a focus event in the child component, and also in the input field too, as the child component already will bind its focus event to the input so the focus event will be called twice, as the input is the root element.

Just removing the focus event from the input will solve the issue.

https://stackblitz.com/edit/vue-676vsb?file=src/components/InputField.vue

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading