Eug*_*ene 2 input setfocus vuejs3 vue-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>
Run Code Online (Sandbox Code Playgroud)
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()
})
}
Run Code Online (Sandbox Code Playgroud)
I also tried using the below.
HTML:
<div>
<input type="text" ref="filter_fld" v-model="filter">
</div>
Run Code Online (Sandbox Code Playgroud)
And in setup() function:
setup() {
const filter_fld = ref(null)
onMounted(() => {
filter_fld.value?.focus()
})
}
Run Code Online (Sandbox Code Playgroud)
But also to no success unfortunately. Any suggestions?
Have an input with a ref in your template e.g.:
<input ref="filter" />
Run Code Online (Sandbox Code Playgroud)
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
};
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用autofocus本机的 HTML 属性:
<input type = "text" id = "filter" v-model = "filter" autofocus/>
Run Code Online (Sandbox Code Playgroud)