Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

90
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda