Now from the parent component I want to run the" /> Now from the parent component I want to run the" /> Now from the parent component I want to run the"/>

Vue.js with TypeScript - getting the type of the ref child component

1.3k views Asked by At

My parent component has a child component called with reference passed to it:

<child
  ref="childRef"
/>

Now from the parent component I want to run the function which is inside child component like this:

mounted() {
  (this.$refs.childRef as any).testFunction();
}

Of course it's working fine with any type, but how do I set the correct type to run this function?

If I use the type of the component itself:

(this.$refs.childRef as Child).testFunction();

it still says that property testFunction does not exist on type 'Vue'.

I use the 2 version of Vue.js.

My child component:

@Component({})
export default class Child extends Mixins(CustomMixin) {
  testFunction() {
    console.log('test');
  }
}

EDIT: Also I found this solution to run the function:

(this.$refs.childRef as Child & { testFunction:() => void }).testFunction();

It updates the Child type with the method testFunction() and it actually works. Although I don't know if this is a good approach.

4

There are 4 answers

3
Rohìt Jíndal On

Your code looks fine and it should work as child component ref holds the instance of Child component only. Here is the code snippet. Please have a look and crosscheck with your code to find out the root cause.

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <child ref="childCom"></child>
</div>

Vue.component('child', {
    methods: {
    testFunction() {
        console.log('test function call')
    }
  }
});

var app = new Vue({
  el: '#app',
  mounted() {
    (this.$refs.childCom as Child).testFunction();
  }
});

Demo Link : https://jsfiddle.net/w6bjso78/

0
The50 On

So far this is the solution I found:

(this.$refs.childRef as Child & { testFunction:() => void }).testFunction();

It works although I don't know if this is a clean apporach. It updates the Child type with a void method testFunction.

0
Lin On

I solved this problem with this:

const MyComponent = ref<InstanceType<typeof MyFileBoard>>()

You can read more details there.

0
Carlos Sanchez Acero On

I always using setup and lang="ts"

I think that the best method is:

// child-component.vue

export interface IEtapa {
  fetchEnviosContar(): Promise<void>
}

const fetchEnviosContar = async ():Promise<void>=>{
  console.log("hello world")
})
defineExpose<IEtapa>({
  fetchEnviosContar,
})

// parent-component.vue

import Etapas, { IEtapa } from '../components/etapas/index.vue'

const refEtapasComponent = ref<IEtapa | null>(null)

refEtapasComponent.value?.fetchEnviosContar()