10

How can I set the focus on an HTML input field upon page loading while using the Composition API of VueJS 3? I have the following HTML:

<div>
  <input type="text" id="filter" v-model="filter">
</div>

And have tried this in the setup() function, but that doesn't set the focus:

setup() {
  onMounted(() => {
    const filter_fld = document.getElementById('filter')
    filter_fld.focus()
  })
}

I also tried using the below.
HTML:

<div>
  <input type="text" ref="filter_fld" v-model="filter">
</div>

And in setup() function:

setup() {
  const filter_fld = ref(null)

  onMounted(() => {
    filter_fld.value?.focus()
  })
}

But also to no success unfortunately. Any suggestions?

2 Answers 2

21

Have an input with a ref in your template e.g.:

<input ref="filter" />

Then after component is mounted focus it by reference on next tick:

import { ref, onMounted, nextTick } from 'vue';

setup() {
  const filter = ref(null);

  onMounted(() => {
    nextTick(() => {
      filter.value.focus();
    });
  });

  return {
    filter
  };
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hero!! Thanks a lot. Didn't know the nextTick() function.
This code is for vue2, not vue3 composition api?
8

You can also use the autofocus native's HTML attribute:

<input type = "text" id = "filter" v-model = "filter" autofocus/>

2 Comments

This only works when the page was loaded the first time. On the next succeeding loads, this will not work. This is Vue. Not native HTML.
It will work for a single web app with a single route. If your site has multiple routes, you might need to focus the form using the nextTick() function on a reload. Vue is a JS framework, it literally controls native HTML.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.