search

Home  >  Q&A  >  body text

Why does Vue 3 child component trigger focus event twice?

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粉005134685P粉005134685328 days ago488

reply all(1)I'll reply

  • P粉191323236

    P粉1913232362024-01-03 00:46:18

    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

    reply
    0
  • Cancelreply