Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set initial focus on input field on page load (with VueJS 3 using Composition API)

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?

like image 351
Eugene Avatar asked Dec 17 '22 11:12

Eugene


2 Answers

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
  };
}
like image 110
rits Avatar answered Dec 27 '22 12:12

rits


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

<input type = "text" id = "filter" v-model = "filter" autofocus/>
like image 37
Erik Martín Jordán Avatar answered Dec 27 '22 11:12

Erik Martín Jordán