Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofocus input on mount (Vue)- iOS

I would like to trigger the input box to focus (and thus keyboard to pop up) when a Vue component appears.

It does not to work on iOS.

I tried using Vue's example directive (here), and HTML5 autoFocus but neither worked.

I created this example in a sandbox (https://codesandbox.io/s/lw321wqkm).

FWIW, I do not believe it is a JS limitation, as I've seen example work (such as React Native Web using autoFocus- see example)

Parent component

<template>
<div>
  <TextComp v-if='showText' />
  <button @click='showText = !showText'> Show/hide input </button>
</div>
 
</template>
 ...
 

Child component

<template>
<div>
   <input ref='focusMe' type='text'/>
</div>
 
</template>
 
<script>
 
export default {
  name: 'TextComp',
  mounted () {
    this.$refs.focusMe.focus()
  }
}
 
</script>
like image 611
Ycon Avatar asked Aug 20 '18 00:08

Ycon


1 Answers

I hope you must have found a solution by now.

But I just wanted to add this for other new users like me.

mounted () {
    this.$refs.focusMe.focus()       // sometime this doesn't work.
  }

Try adding this instead.

this.$nextTick(() => this.$refs.focusMe.focus())

For more info check this

Edit: 14/06/2022

Prashant's answer also helped me understand the nextTick in more depth.

nextTick allows you to execute code after you have changed some data and Vue.js has updated the virtual DOM based on your data change, but before the browser has rendered that change on the page.

like image 120
Debu Shinobi Avatar answered Nov 01 '22 15:11

Debu Shinobi