How to Auto Focus Modal Input Field in Vue.js

Published on December 21, 2019 53 sec read

We're available to do freelance project. Take a look at our services!

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.

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

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:


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 () {

The full script looks like:

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

That’s all. Thanks for reading. 🙂


Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.


Leave a Reply

Your email address will not be published. Required fields are marked *