Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Vue.js [V3] How to focus an element located in a parent component

I currently have the following HTML tree:

<!-- App.vue -->
<main>
  <!-- Header.vue -->
  <header>
     <!-- Nav.vue -->
     <nav>
        <button type="button">Click here should focus on the <a> link</button>     
     </nav>
  </header>
  <a ref="link" tabindex="0">External link</a>
</main>

When clicking on the button, I need to focus on the <a>. How can I get the reference to this link in my Nav.vue file ?

I can do something like this.$parent.$parent.refs.link.focus() but that is not very maintainable and I would rather not.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can achieve this by using event emitting.

Nav.vue

<template>
  <button 
    @click="$emit('handleFocus')"
    type="button"
  >
    Click here should focus on the <a> link
  </button>
</template>

Parent Component

<template>
  <main>
    <Header>
      <!-- Nav.vue -->
      <Nav @handle-focus="handleFocus" />
    </Header>
    <a ref="link" tabindex="0">External link</a>
  </main>
</template>

<script>
export default {
  methods: {
    handleFocus() {
      this.$refs.link.focus()
    }
  }
}
</script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading