Home > OS >  Vue change focus to input on router change
Vue change focus to input on router change

Time:06-22

I have 2 Components Login and Register each input field I have included the autofocus attribute. But when I change the route from the Register component to the Login component autofocus doesn't work. I know this is because the page doesn't reload. But is there any way to do so?

This is my Login.vue, Same as the Register.vue

<form>
   <input type="text" autofocus />  
   <RouterLink to="/login">Login now!</RouterLink>       
</form>  

     
                   
                    

CodePudding user response:

You can use $refs to access your input element with JS :

<form>
   <input type="text" autofocus ref="myInput"/>  
   <RouterLink to="/login">Login now!</RouterLink>       
</form>  

then, watch the route change and can trigger focus() accordingly

watch:{
    $route (to, from){
        if(to !== from){
           this.$refs.myInput.focus()
        }
    }
} 
 

For composition api it should be something like this depending on how you use router:

setup(){
  const myInput = ref(null)
  const route = useRoute()

  watch(route.value, (to, from) => {
      if(to !== from ){
       myInput.value.focus()
      }
    });

}


CodePudding user response:

When you navigate to another page, vue-router doesn't actually reload the page. You need to assign the location in JavaScript to go to another page. You can do this by creating a function in your setup script to navigate to a new location. In the example below, I use web hash for navigation, so you may need to implement different functionality to your code.

<script setup>
  // declare the navigation function
  function nav(path) {
    location = path
  }
</script>

<template>
  <input type="text" autofocus>
  <!-- Navigate to #/about on click -->
  <button @click="nav('#/about')"></button>
</template>
  • Related