Vue - Keep input focused on route change

Viewed 43

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.

1 Answers

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();
}
Related