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

Focus on an input after div mounted Vue

When I click on a button the modal will show. The modal contains an input field. I want to set the focus to the input field inside the modal when the modal appears after clicking.

This is the button so when I click it the modal shows,

<div 
    class="manu-bar-card"
    @click="
       () => {
         groupHandler.addNewgroupModal = true;
         newGroupName.focus();
    }"
 >

This is my modal (This will show if groupHandler.addNewgroupModal is true),

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

<div class="modal-container" v-if="groupHandler.addNewgroupModal">
 <input
        ref="newGroupName"
        type="text"
    />
</div>

This is the input field inside the modal I have set a ref attribute to it,

<input
    ref="newGroupName"
    type="text"
/>

I have registered that ref inside my <script setup> and the reactive object to show/hide modal,

const newGroupName = ref();
const groupHandler = reactive({
  addNewgroupModal: false,
});

I think the reason for not focusing on the input field is modal is not mounted yet when the focus method is called. How to handle such a thing. Appreciate it if somebody could help. Thanks

>Solution :

Your modal should be a separate component.

Let’s call it <Modal v-if="groupHandler.addNewgroupModal" />

Inside the Modal component, You can make a ref for your input, and in the onMounted function, you can call newGroupName.value.focus()

If you don’t want to separate the modal to a saperate component for some reason.

You can use nextTick

<div 
    class="manu-bar-card"
    @click="clickHandler"
 >

And in the setup script.

<div 
    class="manu-bar-card"
    @click="
       () => {
         groupHandler.addNewgroupModal = true;
         newGroupName.focus();
    }"
 >

And in your setup script.

import { nextTick } from 'vue'

const clickHandler = async () => {
  groupHandler.addNewgroupModal = true;
  await nextTick()
  newGroupName.value.focus();
}
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