Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Armani's avatar
Level 17

Add event listener once on repetitive component

I have a VueJs component that will be added by user several times in a page by clicking on a button, it has v-for directive on the component on the main page. inside the component I have a event listener like this:

onMounted(() => {
    document.addEventListener('keydown', (e) => {
        console.log('event added')
    })
})

So if user add 4 instances of the component 4 events will be added to the page, hopefully I can give the message about the problem.

How can I solve this problem.

0 likes
3 replies
tykus's avatar

It is not clear what you're trying to achieve; maybe the keydown event listener needs to be registered on the parent component rather than on the dynamic children?

martinbean's avatar

@armani What does the component actually do on a keydown event? As it may be better to just emit an event from those components to a common parent component:

<!-- child-component.js -->
<script setup>
const emit = defineEmits(['key-down']);
</script>

<template>
    <input v-on:keydown="emit('key-down', event.target.key)">
</template>
<script setup>
const onKeyDown = (key) => {
    // Do something when a key is pressed in a child-component...
};
</script>

<template>
    <parent-component>
        <child-component v-on:key-down="onKeyDown"></child-component>
        <child-component v-on:key-down="onKeyDown"></child-component>
        <child-component v-on:key-down="onKeyDown"></child-component>
    </parent-component>
</template>

If this is just listening for keypresses from custom inputs, then you’d probably be better off using v-model instead of trying to listen for keydown events.

Armani's avatar
Level 17

@martinbean on key down it will set focus on a input inside same component and checks if the component index is the last one:

onMounted(() => {
    document.addEventListener('keydown', (e) => {
        if (e.key === 'End' && props.index === form.fields.details.length - 1) {
            document.getElementById(`quantity${props.index}`)?.focus();
        }
    })
})

<input type="number" min="1" :id="`quantity${props.index}`" class="form-control" v-model="props.current.quantity" >

Please or to participate in this conversation.