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粉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