Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

98
Vistas
Vue - Keep input focused on route change

I have a TopNavBar component, that is present on every route. This component includes a search input field. When a user clicks on the input field the route changes from /bar to /foo but input focus is lost. How can I (re)focus on the input?

TopNavBar.vue

<template>
   <input type="search" name="search-library" v-focus ref="searchInput" @focus="initSearch". />
</template>

<script setup>
const searchInput = ref(null);

<input type="search" name="search-library" v-focus ref="searchInput" @focus="initSearch". />

function initSearch() {
  if (router.currentRoute.value.name != "/foo") {
    router.push({ path: "/foo", query: { initSearch: true }, key: route.fullPath });
  }
}

watch(
  () => router.currentRoute.value.path,
  (newRoute) => {
    if (newRoute == "/foo") {
      searchInput.value.focus();
    }
  }
);
</script>

I'm using Vue3 and Nuxt3. v-focusz directive is declared globally in /plugins` folder and works as expected.

Update

TopNavBar is inside Nuxt 3 layout. Also, upon further investigation I've realised that the input does focus on route change but immediately loses it again.

almost 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You can achieve this by using $refs, Attach a reference on input element and then call focus method on it.

In template:

<parent-component>
  <search-component ref="searchComponentRef" />
</parent-component>

In script:

mounted() {
  this.$refs.searchComponentRef.$el.focus();
}
almost 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda