N
Nuxt7mo ago
cak malik

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
Reinier Kaper
Reinier Kaper7mo ago
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?
JonathanDoerfler
You have to use searchInput.value?.input.focus() 🤓
LazyDali
LazyDali7mo ago
Maybe you need the nextTick thingy after onMounted? Is the searchInput ready and available?
pile
pile7mo ago
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
LazyDali
LazyDali7mo ago
And I see that there is a native HTML attribute called autofocus
LazyDali
LazyDali7mo ago
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.
cak malik
cak malikOP6mo ago
Ohhhh.. this solved after restart PC. sounds funny. even though I had closed the terminal and run bun run dev again
Want results from more Discord servers?
Add your server