Can't use ref for focus input (SOLVED)
why doesnt work with nuxt
this is my code
const searchInput = ref<HTMLInputElement | null>(null);
onMounted(() => {
searchInput.value?.focus();
});
and i got error
500
searchInput.value.focus is not a function
7 Replies
Are you sure the error originates in that code? Because the optional chaining should already take care of that
Oh you might need
?.focus?.()
But why would that ref not exist on mount? Does it have a v-if or something?You have to use
searchInput.value?.input.focus()
🤓Maybe you need the nextTick thingy after onMounted?
Is the searchInput ready and available?
Have you tried using the vueuse useFocus composable? https://vueuse.org/core/useFocus/
It may be easier because it watches the ref automatically if it's not null, and then places focus on the element. You can set initial focus on it as described in that documentation
VueUse
Collection of essential Vue Composition Utilities
And I see that there is a native HTML attribute called
autofocus
Be aware that manipulating the autofocus has an accessibility concern (if it applies to your criteria) . ref https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/autofocus
MDN Web Docs
autofocus - HTML: HyperText Markup Language | MDN
The autofocus global attribute is a Boolean attribute indicating that an element should be focused on page load, or when the that it is part of is displayed.
Ohhhh.. this solved after restart PC.
sounds funny. even though I had closed the terminal and run bun run dev again