Stopbyte

How To Focus An Input In Vue?

1-How to Set Focus on an Input in Vue?

Sometimes it’s important to set focus on input (programmatically or by default), it is often for accessibility, and/or to make the app more convenient to use purposes.

the usual is setting it to be autofocused at Page load:

<input type="text" placeholder="I'm auto-focused" autofocus>

The only problem is that when you add the autofocus attribute to an input it will be focused once is loaded, but when you init a Vue app the focus is lost so you need to programmatically focus an element.

To use focus() programmatically you use either Vuejs or vanilla javascript:

→ in Javascript:

#html 
    <form>
      <input id="email" />
    </form>

Now grap you element using getElementById()

const input = document.getElementById('email');

Now all you have to do is to call the focus() function:

input.focus( *options* ); // Object parameter

→ in Vue.js:
Vue offers a better and easy way:

#vue template
   <template>
     <input ref="email" />
   </template>

note: Vue uses ref="something" attribute to register a reference to any HTML element or child component.

Then you use $refs, which are a much more reliable way of grabbing your elements.

const input = this.$refs.email;

Now you are allowed to use that within your method:

    methods: {
        focusInput() {
          ...
          this.$refs.email.focus();
        }
      }

Note: if you are using a Custom component you likely get this error: “focus is not a function”.
to fix this you need to make sure you are getting the root element of your custom component $el :
import CustomInput from ‘./CustomInput.vue’;

export default {
  components: {
    CustomInput,
  },
  methods: {
    focusInput() {
      this.$refs.email.$el.focus();
    }
  }
}

You may still run into some issues though…because sometimes you will have to wait for Vue to finish re-rendering.

For instance, if you change the inputs’ status from being hidden to being displayed.
You’ll need to wait for the input to be rendered before you can grab it and focus on it.

To do this you can use a method to check if the element you want to focus Is visible or not.
Here is an example:

<template>
  <div>
    <CustomInput v-if="inputIsVisible" ref="email" />
  </div>
</template>
<template>
  <div>
    <CustomInput v-if="inputIsVisible" ref="email" />
  </div>
</template>
import CustomInput from './CustomInput.vue';

export default {
  components: {
    CustomInput,
  },
  data() {
    return {
      inputIsVisible: false,
    };
  },
  mounted() {
    this.focusInput();
  },
  methods: {
    showInput() {
      // Show the input component
      this.inputIsVisible = true;

      // Focus the component, but we have to wait
      // so that it will be showing first.
      this.nextTick(() => {
        this.focusInput();
      });
    },
    focusInput() {
      this.$refs.email.$el.focus();
    }
  }
}

You can see that we have called our focusInput() method withing nextTick().
nextTick allows us to wait until the input is rendered in the DOM. Once it’s there, you will be able to grab it and focus on it.
you can read more about nextTick here https://vuejs.org/v2/api/#Vue-nextTick.

→ other ways to do it:

Sometimes when the input is not the root element of that el-input component (probably wrapped in a

), you will have to get it from the children of the root element.
this.$refs.input.$el.children[0].focus();

another trick is to set a time out (using setTimeout), until the re-render finishes here is an example:

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

 methods: {
    setFocus: function() {
      // Note, you need to add a ref="input" attribute to your input.
      this.$refs.input.focus();
    },

 created() {
    setTimeout(x => {
      this.$nextTick(() => this.setFocus()); // just watch out with going too fast !!!
    }, 1000);

using the same way above you can pass props to your component,

<input-text ref="name" v-model="item.name"></input-text>
watch: {
      dialog (val) 
         if (val) {
            setTimeout(() => {
               this.$refs.name.focus();
            }, 10);
         }
      }
 }
2 Likes