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

Time:11-03

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.

CodePudding user response:

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>
  • Related