Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

96
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!