How to Auto Focus Modal Input Field in Vue.js

Hi developers, sometimes we need to autofocus an input field of modal. In this short article, I’ll show how to set autofocus an input field of modal.

Template Part

We want to set focus on an input field on modal open. Let’s take a button & a modal. On click button, we’ll show the modal.

<template>
  <div id="app">
    <!-- button -->
    <button class="button" @click="showModal">Button</button>
    <!-- modal -->
    <div class="modal" v-bind:class="{'is-active':isModalOpen}">
      <div class="modal-content">
        <input type="text" ref="search" name="search">
      </div>
    </div>
  </div>
</template>

Script Part

We’ve set ref="search" in the input field. Ref is used to register or indicate a reference to the HTML element or child element in the template.

Without modal we can focus an input field using this:

this.$refs.search.focus()

To set autofocus in modal, we’ll use $nextTick() method. Please read the official documentation about $nextTick(). So, this is the code for modal:

this.$nextTick(function () {
    this.$refs.search.focus()
})

The full script looks like:

<script>
export default {
  name: 'app',
  data() {
    return {
      isModalOpen: false,
    }
  },
  methods: {
      showModal() {
          this.isModalOpen = true
          // auto focus
          this.$nextTick(function () {
              this.$refs.search.focus()
          })
      }
  },
}
</script>

That’s all. Thanks for reading.


Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.