Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Lars-Janssen's avatar

vue.js set focus on textfield

Hello,

How can I set focus on an input field in vue.js. I can't get it working... And cannot find it in documentation?

0 likes
9 replies
davorminchorov's avatar

auto focus? use autofocus on the input tag as an attribute.

<input type="text" autofocus />
2 likes
jekinney's avatar
jekinney
Best Answer
Level 47

Single page style app?

I sgguest useing v-bind to set autofocus from false (default) to true when the component loads (ready()) inside a nextTick.

Basically what this plugin does. https://github.com/simplesmiler/vue-focus/blob/master/dist/vue-focus.js

As the page isn't refreshed and its entering the Dom the browser isn't exacuting the autofocus. But it will after the page is rendered on nextTick.

1 like
alphaelf's avatar

if you use Vue 2 and need set focus programmatic, use ref directive

<input type='search' ref='search' placeholder='Keyword:'>

<script>
export default{
   mounted(){
       this.$refs.search.focus();
   }
}
</script>

UPDATED: use mounted instead of created tanks to @xkrupa12 for it.

11 likes
xkrupa12's avatar

@alphaelf focus() should be called inside mounted() function, since in created(), ref might not be present yet.

1 like
jonecir's avatar

Hi, the code below does not work for me.

mounted() { this.$refs.search.focus(); }

williamoliveira's avatar

I simply did this and works great

<template>
   <input type="text" v-focus>
</template>

<script>
 const focus = {
    inserted(el) {
      el.focus()
    },
  }

  export default {
    directives: { focus },
    // ... 
  }
</script>
4 likes
alexman's avatar

Sometimes you need to call focus in the next tick

    this.$nextTick(() => this.$refs.search.focus())
9 likes

Please or to participate in this conversation.