Home > Net >  How to get the ref which is in a child component in vue?
How to get the ref which is in a child component in vue?

Time:09-17

I'm trying to access a ref from a parent component which is defined in the child component. I've got a file where I call the parent component and inside of the component I call 2 child components like so:

<my-component>
    <component-header></component-header>
    <component-content></component-content>
</my-component>

Inside my-component I've got a <slot></slot> and no other html, but that is where I need to call a ref which is listed in the component-header. Here is my component-header file:

<template>
  <div ref="mycomponentHeader">
    <slot>
      // Here some other html
    </slot>
  </div>
</template>

How will I be able to call the mycomponentHeader ref inside the my-component parent? I've tried calling the ref like this:

      console.log(this.$parent.$refs.mycomponentHeader)
      console.log(this.$refs.mycomponentHeader)
      console.log(this.$refs)
      console.log(this.$children.$refs.mycomponentHeader)

But these resulted in an undefined, an empty object and a cannot read properties of undefined (reading '$refs'). Any help would be appreciated!

CodePudding user response:

You can simply achieve that by assigning a ref into a child component element and then access the child component inner ref variable from the parent component.

In parent component template :

<parent-component>
  <child-component ref="childComponent"/>
<parent-component>

In script :

mounted() {
  console.log(this.$refs.childComponent) // Here you can access any properties or methods of a child component.
}

Live Demo :

Vue.component('child', {
  props: ['childmsg'],
  template: '<div ref="mycomponentHeader">{{ childmsg }}</div>',
  methods: {
    getChildRef() {
        return this.$refs.mycomponentHeader;
    }
  }
});

var app = new Vue({
  el: '#app',
  mounted() {
    console.log(this.$refs.childComponent.getChildRef().textContent)
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <child ref="childComponent" childmsg="This is a child message">
  </child>
</div>

CodePudding user response:

<my-component>
    <component-header ref="header"></component-header>
    <component-content></component-content>
</my-component>



mounted(){
  this.$refs.header.$refs.mycomponentHeader
}
  • Related