I only started coding with vue.js
yesterday, and I don't know how to "focus" on a textbox without using the "traditional" JS way, which is document.getElementById('myTextBox').focus()
.
Initially, my textbox is hidden. I have a "Start" button, and when the user clicks on it, the textbox is then displayed, and I want to set the focus
there, so to speak. I already tried using ref
, but to no avail (see code below).
HTML:
<input id="typeBox" ref="typeBox" placeholder="Type here..." />
Javascript
export default {
name: 'game',
methods: {
startTimer () {
setTimeout(function () { /* .focus() won't work without this */
/* ugly and not recommended */
// document.getElementById('typeBox').focus()
/* Throws the error: Cannot read property 'typeBox' of undefined */
this.$refs.typeBox.focus()
// ... any other options?
// ...
}, 1)
}
} /* END methods */
} /* END export default */
Does anyone know how to do this? Please help.
UPDATE:
Adding autofocus
on input
does the trick of focusing right after the page is loaded. But in my app, there is a need to "refocus" on the input field several times without reloading the page, that's why I need a way to call .focus()
.