Why does Vue 3 child component trigger focus event twice?
P粉005134685
P粉005134685 2024-01-02 09:44:07
0
1
485

When I trigger the 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 expected).

But when you put the same input field into a child component and focus it:

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

...The event is triggered twice.

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

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

P粉005134685
P粉005134685

reply all(1)
P粉191323236

Therefore, you should not put the focus event in the child component, nor in the input field, because the child component has already bound its focus event to input, so the focus event will be called twice because input is the root element.

Simply removing the focus event from the input will solve the problem.

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template