Anna F
Anna F

Reputation: 1683

How can I access the method of a child component?

I have a child component, which is built into the parent. I want to access the child's method from the parent. I want to use $refs for this purpose.

Template:

<template>
  <div>Parent!</div>
</template>

Script:

<script>
    Vue.component('child',{
      template: `<div>I am child</div>`,
    }
    export default {
       name: 'Parent'
    }
</script>

How could I declare $refs for my child in this case?

Upvotes: 1

Views: 53

Answers (1)

Ana Liza Pandac
Ana Liza Pandac

Reputation: 4861

To achieve that, you can assign a reference ID to the child component using the ref attribute.

<template>
  <div>Parent!</div>
  <child ref="childComponent"/>
</template>

Now you can get access to your child component instance from your parent component by using it as such:

this.$refs.childComponent // where componentName is the ref value

That also means you can execute the methods that you defined under your child component.

this.$refs.childComponent.myFunction();

See docs for more details.

Upvotes: 3

Related Questions