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?
auto focus? use autofocus on the input tag as an attribute.
<input type="text" autofocus />
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.
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.
@alphaelf focus() should be called inside mounted() function, since in created(), ref might not be present yet.
Hi, the code below does not work for me.
mounted() {
this.$refs.search.focus();
}
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>
Sometimes you need to call focus in the next tick
this.$nextTick(() => this.$refs.search.focus())
Please or to participate in this conversation.