Home > Blockchain >  Focus on an input after div mounted Vue
Focus on an input after div mounted Vue

Time:07-19

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 
    
    @click="
       () => {
         groupHandler.addNewgroupModal = true;
         newGroupName.focus();
    }"
 >

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

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

CodePudding user response:

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 
    
    @click="clickHandler"
 >

And in the setup script.

<div 
    
    @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();
}
  • Related